linux ------- thread

  

  To connect pthread library when compiling: gcc main.cpp -o main -lpthread 

 

 

1. thread identification

  Process ID unique throughout the system, but the thread ID is meaningful only in the context of the process belongs

  Type: pthread_t, use special compare function (different types of system implementation is not the same, linux unsigned long integer, solaris unsigned integer, FresBSD and the Mac pointer pointing mark indicates pthread)

(1) Compare the thread ID

  

 

   Equal returns a non-zero; returns ranging from 0

(2) obtain their ID

  

 

   

2. Create a thread

  

  Successful return 0; failure to return error number

  parameter:

    attr to set thread attributes

    start_routine: This function creates a new thread starts running from the arg parameter is, if a plurality of parameters, the parameters put in place a structure, then the structure of the address passed arg

 

3. Thread Termination

  A single process out of the way:

    ① start the program returns from

    ② other threads in the same process is canceled  

    ③ thread calls pthread_exit

 

(1) thread exit

  

 

   Normal exit, retval storage return code; the other thread was canceled, retval is set to PTHREAD_CANCELED

(2) termination of the waiting thread

  

 

   

(3) cancel threads

  

 

  Request to cancel other threads in the same process. Successful return 0; failure to return error number

  thread the threads can choose to ignore cancel or control how it is canceled

 

(4) clean up the thread / thread withdraw from the program

  

 

  When a thread performs the following actions by scheduling cleanup function routine :( pthread_cleanup_push thread return return with its launcher, the cleanup function is not called)

    ① thread calls pthread_exit

    ② response to a cancellation request

    Pthread_cleanup_pop ③ When invoked with a non-parametric 0 execute

  execute 0, remove the top of a clean-up function

 Test routines:

 1 #include <stdio.h>
 2 #include <pthread.h>
 3 
 4 void cleanup(void *arg)
 5 {
 6     printf("cleanup:%s\n",(char *)arg);
 7 }
 8 
 9 void thr_fn1(void *arg)
10 {
11     printf("thread 1 start\n");
12     pthread_cleanup_push(cleanup,"thread 1 first handler");
13     pthread_cleanup_push(cleanup,"thread 1 second handler");
14     printf("thread 1 push complete\n");
15     if(arg) {
16         return ((void *)1);
17     }
18     pthread_cleanup_pop(0);
19     pthread_cleanup_pop(0);
20     return ((void *)1);
21 }
22 
23 void thr_fn2(void *arg)
24 {
25     printf("thread 2 start\n");
26     pthread_cleanup_push(cleanup,"thread 2 first handler");
27     pthread_cleanup_push(cleanup,"thread 2 second handler");
28     printf("thread 2 push complete\n");
29     if(arg) {
30         pthread_exit((void *)2);
31     }
32     pthread_cleanup_pop(0);
33     pthread_cleanup_pop(0);
34     pthread_exit((void *)2);
35 }
36 
37 int main(void)
38 {
39     int err;
40     pthread_t tid1,tid2;
41     void *tret;
42     err = pthread_create(&tid1,NULL,thr_fn1,(void *)1);
43     if(err != 0) {
44         printf("cant create thread 1\n");
45         exit(1);
46     }
47     err = pthread_create(&tid2,NULL,thr_fn2,(void *)1);
48     if(err != 0) {
49         printf("cant create thread 2\n");
50         exit(2);
51     }
52     err = pthrad_join(tid1,&tret);
53     if(err != 0) {
54         printf("cant join thread 1\n");
55         exit(1);
56     }
57     printf("thread 1 exit code:%ld\n",(long)tret);
58     err = pthrad_join(tid2,&tret);
59     if(err != 0) {
60         printf("cant join thread 1\n");
61         exit(1);
62     }
63     printf("thread 2 exit code:%ld\n",(long)tret);
64     return 0;
65 }

 

 

 

(5) separating thread

  Default state is saved to the thread terminates the call pthread_join thread, if the thread is separated, the thread of the underlying storage resources can be withdrawn as soon as the thread terminates. It can not be separated by threads pthread_join

  

 

 

 

 

4. Thread Synchronization

  Each thread has thread ID, a set of register values, stack, scheduling priority, a signal mask character, variable errno. All threads in the process all the information that process are shared, including executable code, global Kitamura, heap memory, stack, file descriptors.

 

  No synchronization routines: two threads to operate a global variable ticket_num

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4 #include <pthread.h>
 5 
 6 int ticket_num = 10;
 7 
 8 void *sell_ticket(void *arg)
 9 {
10     int i = 0;
11     for(;i<10;i++) {
12         if(ticket_num>0) {
13             sleep(1);
14             printf("sell the %dth ticket\n",10-ticket_num+1);
15             ticket_num--;
16         }
17     }
18     return 0;
19 }
20 
21 int main()
22 {
23     int flag,i;
24     pthread_t tids[2];
25     for(i=0;i<2;i++) {
26         flag = pthread_create(&tids[i],NULL,sell_ticket,NULL);
27         if(flag != 0) {
28             printf("pthread create error,flag:%d\n",flag);
29             exit(flag);
30         }
31     }
32     sleep(10);
33     for(i=0;i<2;i++) {
34         flag = pthread_join(tids[i],NULL);
35     }
36     return 0;
37 }

  result:

  

 

 

 

  4.1 mutex mutex

  It is essentially a lock on the mutex lock before accessing a shared resource, after visiting unlock.

(1)

  Mutex statically allocated, can be set to a constant PTHREAD_MUTEX_INITIALIZER initialization, or initializing function pthread_mutex_init

  Dynamic allocation (such as a malloc ()), before the release of the memory to be called pthread_mutex_destroy

  

 

  

   abstime specifies an absolute time willing to wait / blocked (if more than this time, no longer mutex lock, but returns an error code ETIMEDOUT)

(2) Properties mutex

  Set and get the mutex attributes:

  

 

  pshared: mutex shared property ①PTHREAD_PROCESS_PRIVATE, can only be used within a process two threads are mutually exclusive

                 ②PTHREAD_PROCESS_SHARED, between threads can be used in different processes of mutual exclusion, mutex lock to be allocated in the process of shared memory in use, and then set the properties of the lock   

(3) Type

  

 

  kind: the mutex type

    ①PTHREAD_MUTEX_NOMAL, standard mutex

    ②PTHREAD_MUTEX_RECURSICE, recursive mutex (internal counters, once the lock counter is incremented by 1, a lock solution counter is decremented)  

    ③PTHREAD_MUTEX_ERRORCHECK, check the mutex lock and then successfully locked error returns an error message, do not block

    ④PTHREAD_MUTEX_DEFAULT, default mutex     

(4) Features

  ① atomicity: a thread locks a mutex, no other thread can successfully lock the mutex at the same time

  ② uniqueness: a thread mutex is locked until unlocked, no other thread can lock the mutex

  ③ non-peak waiting for: the first thread mutex is locked, and the second thread tries to lock, the second thread is suspended until the first thread in contact with the lock, the second thread wakes up

(4) Operation Process

  ① front and rear access to shared resources critical resource, lock

  After the completion of access ② release the lock on the mutex

(5) deadlock

  ① a second thread tries to lock the same mutex 

  ② two mutex, occupies a first thread A mutex is suspended when attempting to lock the second mutex; second thread B occupies the mutex, the first attempts to lock the mutex, It is suspended. Then thread A, B can not continue to run, resulting in deadlock

     Solution: Use trylock method, if successful, continue to run; if trylock fails, the lock has to release, and then try again after some time  

 

  Use mutex routines:

    Change: acquire the lock before the test to shared resources ticket_num testing, operation, operation after the release of the lock line 7,14,20

. 1 #include <stdio.h>
 2 #include <stdlib.h>
 . 3 #include <unistd.h>
 . 4 #include <pthread.h>
 . 5  
. 6  int ticket_num = 10 ;
 . 7 pthread_mutex_t mutexa = PTHREAD_MUTEX_INITIALIZER;   // static initializer mutual lock repellent 
. 8  
. 9  void * sell_ticket ( void * Arg)
 10  {
 . 11      int I = 0 ;
 12 is      for (; I < 10 I ++; {)
 13 is          // acquiring the lock before the operation of competing for resources, test 
14         pthread_mutex_lock(&mutexa);
15         if(ticket_num>0) {
16             sleep(1);
17             printf("sell the %dth ticket\n",10-ticket_num+1);
18             ticket_num--;
19         }
20         pthread_mutex_unlock(&mutexa);
21     }
22     return 0;
23 }
24 
25 int main()
26 {
27     int flag,i;
28     pthread_t tids[2];
29     for(i=0;i<2;i++) {
30         flag = pthread_create(&tids[i],NULL,sell_ticket,NULL);
31         if(flag != 0) {
32             printf("pthread create error,flag:%d\n",flag);
33             exit(flag);
34         }
35     }
36     sleep(10);
37     for(i=0;i<2;i++) {
38         flag = pthread_join(tids[i],NULL);
39     }
40     return 0;
41 }

  operation result:

  

 

 

 

  4.2 Variable Conditions

  Mutex lock for, wait for condition variable.

  Usage: A thread to wait after the establishment of a condition to continue down the implementation, if the conditions are not satisfied, this thread has been blocked waiting. If the conditions are met for a moment, then wake A continues (if using a mutex, the thread needs to continue to acquire the lock and then judge conditions, low efficiency)  

(1) Initialization

  

 

(2) wait condition is satisfied

  

  wait function was introduced to a mutex locked, the calling thread function automatically placed on the list of threads waiting conditions, unlock the mutex. When the wait function returns, the mutex is locked again.

(3) conditions are met after the notification thread

  

 

(4) Examples of short answer

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4 #include <pthread.h>
 5 
 6 int ticket_num = 10;
 7 pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;  //静态初始化互斥锁
 8 pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
 9 int x = 10,y = 20;
10 
11 void *fun1(void *arg)
12 {
13     printf("thread 1 start\n");
14     pthread_mutex_lock(&qlock);
15     while(x<y) {
16         pthread_cond_wait(&qready,&qlock);
17     }
18     sleep(3);
19     printf("thread 1 exit\n");
20     pthread_exit(NULL);
21 }
22 
23 void *fun2(void *arg)
24 {
25     printf("thread 2 start\n");
26     
27     pthread_mutex_lock(&qlock);
28     x = 20;
29     y = 10;
30     printf("change:x=%d  y=%d\n",x,y);
31     pthread_mutex_unlock(&qlock);
32     if(x>y) {
33         pthread_cond_signal(&qready);
34     }
35     
36     printf("thread 2 exit\n");
37     pthread_exit(NULL);
38 }
39 
40 int main()
41 {
42     pthread_t tids[2];
43     int flag;
44     flag = pthread_create(&tids[0],NULL,fun1,NULL);
45     if(flag != 0) {
46         printf("pthread 1 create error\n");
47         exit(flag);
48     }
49     sleep(2);
50     
51     flag = pthread_create(&tids[1],NULL,fun2,NULL);
52     if(flag != 0) {
53         printf("pthread 2 create error\n");
54         exit(flag);
55     }
56     sleep(5);
57     return 0;
58 }

  Thread 1 first execution, but because conditions are not met, then acquire a mutex and call wait

  Thread 2 started and changed the conditions for the conditions, so call signal notification thread 1, thread 1 to continue running

  

 

 

 

  4.3 Read-Write Lock

(1) and the read-write lock mutex

  Only mutex locked state and an unlocked state, and that only one thread can lock it

  Similarly mutex, but the read-write locks allow multiple threads to occupy the same is read-write lock mode. Allowing only one thread occupy write mode read-write locks. (Adapted to read than to write the number of data structures and more cases)

  There are three write lock state: locking the read mode, write mode locked, unlocked

(2) features

  There are threads in reading, allow other threads to read and write is not allowed

  There are threads in writing, it does not allow other threads to read, write

(3)

  ① initialization, destruction

  

 

  ② apply for a read lock

  

 

  ③ application write lock 

  

 

  ④ Unlock

  

 

  ⑤ with a lock timeout

    Failure to obtain the lock block for only a set time, but not always blocked

  

 

  

 

 

 

  4.4 Semaphore (semaphore set)

  <semaphore.h>

  Mutex allows only one thread to enter the critical section, and the signal may allow multiple threads to enter the amount of

 

  4.5 Spinlocks

  When the lock hold time is short, and do not want the thread (blocking ----- recovery) time spent on such rescheduling, can spin lock. When the threads spin-wait lock is available, it is monopolizing the CPU's  

  

 

 

   

 

 

Guess you like

Origin www.cnblogs.com/taoXiang/p/12453259.html