Inter-thread communication in Linux

Source: Internet
Author: User

There is no special means for communication between threads, because the data structure can be shared between threads, that is, a global variable can be used by both threads at the same time. Note that synchronization between threads is required. mutex is generally used. You can refer to some new Unix/Linux programming books and will mention POSIX thread programming, such as advanced programming for UNIX environments (version 2) and programming for UNIX systems. Messages in Linux belong to IPC, that is, inter-process communication, and threads cannot be used.

Linux uses pthread_kill to send signals to threads. In Windows, post is not used. (do you mean postmessage ?) For thread communication?

Windows uses postthreadmessage for inter-thread communication, but this method is rarely used. The principle of synchronization in some Linux systems is the same as that in windows. However, singal interrupt in Linux is also very useful.

Use the semaphore to share resources.

One of the reasons for using multithreading is that compared with processes, it is a very "frugal" multi-task operation method. We know that in a Linux system, starting a new process must be allocated to it with an independent address space, creating a large number of data tables to maintain its code segment, stack segment, and data segment, this is an "expensive" way of multitasking. While multiple threads running in a process use the same address space for each other to share most of the data. The space required to start a thread is much less than the space required to start a process, in addition, the time required for switching between threads is much less than the time required for switching between processes.

The second reason for using multithreading is the convenient communication mechanism between threads. For different processes, they have independent data space, and data transmission can only be performed through communication. This method is not only time-consuming, but also inconvenient. The thread is not the case. Because the threads in the same process share data space, the data of one thread can be directly used by other threads, which is fast and convenient. Of course, data sharing also brings about other problems. Some Variables cannot be modified by two threads at the same time, and some subprograms declare static data, which is more likely to cause catastrophic damage to multithreaded programs, these are the things you need to pay attention to when writing multi-threaded programs.
1. Simple multi-threaded Program

First in the main function, we use two functions, pthread_create and pthread_join, and declare a variable of the pthread_t type.
Pthread_t has been declared in the header file pthread. H. It is the thread identifier.

The pthread_create function is used to create a thread. The function prototype is as follows:

Extern int pthread_create _ p (pthread_t * _ thread, _ const pthread_attr_t * _ ATTR, void * (* _ start_routine) (void *), void * _ Arg ));

The first parameter is the pointer to the thread identifier. The second parameter is used to set the thread attribute. The third parameter is the starting address of the thread running function, and the last parameter is the parameter of the running function. If our function thread does not require a parameter, the last parameter is set as a null pointer. We also set the second parameter as a null pointer to generate a thread with the default attribute. The setting and modification of thread attributes will be described in the next section. When the thread is successfully created, the function returns 0. If the value is not 0, the thread creation fails. The common error codes returned are eagain and einval. The former indicates that the system restricts the creation of new threads. For example, the number of threads is too large. The latter indicates that the second parameter indicates that the thread attribute value is invalid. After the thread is successfully created, the newly created thread runs the function with parameters 3 and 4, and the original thread continues to run the next line of code.
The pthread_join function is used to wait for the end of a thread. Function prototype:

Extern int pthread_join _ p (pthread_t _ th, void ** _ thread_return ));

The first parameter is the identifier of the waiting thread, and the second parameter is a user-defined pointer, which can be used to store the return value of the waiting thread. This function is a thread-blocking function. The function called will wait until the end of the waiting thread. When the function returns, the resources of the waiting thread will be reclaimed. There are two ways to end a thread. One is that the function ends and the thread that calls it ends, as in the preceding example; another method is to use the pthread_exit function. Its function prototype is:

Extern void pthread_exit _ p (void * _ retval) _ attribute _ (_ noreturn __));

The unique parameter is the return code of the function. As long as the second thread_return parameter in pthread_join is not null, this value will be passed to thread_return. Finally, it should be noted that a thread cannot be waited by multiple threads. Otherwise, the first thread that receives the signal will return success, and the other threads that call pthread_join will return the error code esrch.

2. modify attributes of a thread
The function used to set the thread binding status is pthread_attr_setscope. It has two parameters: the first is the pointer to the attribute structure, and the second is the binding type. It has two values: pthread_scope_system (bound) and pthread_scope_process (unbound ). The following code creates a bound thread.

#include 
pthread_attr_t attr;
pthread_t tid;

/* Initialize the property value, which is set to the default value */
Pthread_attr_init (& ATTR );
Pthread_attr_setscope (& ATTR, pthread_scope_system );

pthread_create(&tid, &attr, (void *) my_function, NULL);

3. Thread Data Processing

Compared with a process, one of the biggest advantages of a thread is data sharing. Each process shares the data segment that follows the parent process to conveniently obtain and modify data. But this also brings many problems to multithreaded programming. We must be careful that there are multiple different processes accessing the same variable. Many functions cannot be reentrant, that is, they cannot run multiple copies of a function at the same time (unless different data segments are used ). Static variables declared in functions often cause problems and return values of functions. If the returned address is the address of the Space statically declared by the function, when a thread calls the function to obtain the address and uses the data pointed to by the address, other threads may call this function and modify this data segment. Shared variables must be defined with the keyword volatile in the process to prevent the compiler from changing their usage methods during optimization (for example, using the-ox parameter in GCC. To protect variables, we must use semaphores, mutex, and other methods to ensure correct use of variables.

4. mutex lock

Mutex lock is used to ensure that only one thread is executing a piece of code within a period of time. Obvious necessity: assuming that each thread writes data to the same file in sequence, the final result must be disastrous.

 

  1. # DEFINE _ gnu_source
  2. # Include <unistd. h>
  3. # Include <pthread. h>
  4.  
  5. # Include <stdlib. h>
  6. # Include <stdio. h>
  7.  
  8. // Static pthread_rwlock_t rwlock = pthread_rwlock_initializer;
  9. // Although it is P/V, it is more convenient to use cond.
  10. Static pthread_cond_t cond = pthread_cond_initializer;
  11. Static pthread_mutex_t mutex = pthread_mutex_initializer;
  12.  
  13. Int I = 0;
  14.  
  15. Void get ()
  16. {
  17. Pthread_mutex_lock (& mutex );
  18. While (I = 0) // lower limit of the queue
  19. Pthread_cond_wait (& cond, & mutex); // wake up other threads for detection.
  20.  
  21. -- I;
  22. Pthread_cond_signal (& Cond );
  23. Printf ("current size: % d/N", I );
  24.  
  25. Pthread_mutex_unlock (& mutex );
  26. }
  27.  
  28. Void put ()
  29. {
  30. Pthread_mutex_lock (& mutex );
  31. While (I = 3) // maximum number of queues
  32. Pthread_cond_wait (& cond, & mutex );
  33.  
  34. ++ I;
  35. Pthread_cond_signal (& Cond); // wake up other threads
  36. Printf ("Now size: % d/N", I );
  37.  
  38. Pthread_mutex_unlock (& mutex );
  39. }
  40.  
  41. Void * THF (void * Arg)
  42. {
  43. While (1)
  44. {
  45. Put ();
  46. }
  47. }
  48.  
  49. Int main ()
  50. {
  51. Pthread_t tid;
  52. Pthread_create (& tid, null, THF, null );
  53.  
  54. Sleep (3 );
  55. While (1)
  56. Get ();
  57. }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.