Thread separation and thread mutex

Source: Internet
Author: User

One. Thread Separation:

    1. Overview:

At any one point in time, the thread is either associative (joinable) or detached (detached). One by one threads can be combined to recover their resources and kill by other threads. Its memory resource (such as a stack) is not freed until it is reclaimed by another thread. Conversely, one by one separate threads cannot be recycled or killed by other threads, and its memory resources are automatically freed by the system when it terminates.

By default, threads are created to be combined. In order to avoid memory leaks, each of the bonded threads should either be displayed with Pthread_join, or be separated by a call using the Pthread_detach function.

The Ps:pthread_join function is waiting in a blocking style, while calling the Pthread_detach function is a non-blocking wait.

2. Related functions:

Pthread_detach function: Pthread_detach (pthread_t thread)

Return value: Successful return 0, failure returns an error number.


3. Related code:

1  #include <stdio.h>  2  #include <stdlib.h>  3  #include < Pthread.h>  4   5 void *create_thread (void *ptr)   6  {  7     pthread_detach (Pthread_self ());  8      printf ("%s", (char *) PTR);   9     return null; 10  } 11  12  13 int main ()  14 { 15      pthread_t tid; 16     int err = pthread_create ( &tid, NULL, create_thread,  "thread is running....\n"); 17      if (err != 0)  18     { 19          printf ("create thread failed,err info is: %s\n",  Strerror (Err));  20 &nbsP;   } 21  22     sleep (1); 23      void *errno = null; 24     int ret = 0 ;  25     ret = pthread_join (Tid, &errno); 26   27     if (ret != 0)  28     { 29          printf ("wait for thread failed, err  Info is: %d\n ", (int) errno); 30     } 31      else 32     { 33          printf ("wait for thread success\n"); 34     } 35      return ret; 36 }                                                                                                                                                                       ~

PS: You can also detach the created thread from the main thread.

Execution Result:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/7F/37/wKioL1cXIzzQuR_mAAApVO_HUq4566.png "title=" 2016-04-20 14:31:07 screen. png "alt=" Wkiol1cxizzqur_maaapvo_huq4566.png "/>


Two. Thread Mutex:

    1. Overview:

In a multithreaded environment, conflicts can occur when multiple threads may have access to shared data at the same time (in relative terms). Because modifying a variable is not an atomic operation, it involves reading the variable from memory, changing the value in the register, writing the value in the register to three steps in memory, and possibly having other threads manipulate the variable in either step. So in multi-threading, one thread is going to operate on a critical section, and a thread mutex is used.

The solution to the thread mutex is to introduce a mutex (Mutex,mutualexclusive lock), the thread that gets the lock can complete the "read-Modify-write" operation, then release the lock to other threads, and the thread that does not get the lock can only wait and not access the shared data, so "read-modify-write" The three-step operation consists of one by one atomic sub-operations, either executing the row, either not executing the row, not executing the line to the middle, or doing this on the other processor side.

In general, if the same thread calls lock two times, in the second call, because the lock is already occupied, the thread suspends waiting for the other thread to release the lock, but the lock is occupied by itself, and the thread is suspended without a chance to release the lock, so it is always suspended waiting, which is called a deadlock ( Deadlock). Another typical deadlock scenario is when thread a obtains lock 1, thread B obtains a lock of 2, and thread A calls lock to attempt to acquire lock 2, and the result is that thread B is required to suspend waiting for thread B to release the lock 2, and at this point, a call to lock tries to obtain lock 1, the result is a suspend wait thread a release lock 1 So threads A and B are always in a suspended state. It is not difficult to imagine that if more threads and more locks are involved, the deadlock problem will become complex and difficult to judge.
When writing a program, you should try to avoid having multiple locks at the same time, and if it is necessary to do so, there is a principle that if all threads acquire locks in the same order when multiple locks are required (most commonly by the order of address of the mutex variable), no deadlock occurs. For example, in a program used to lock 1, lock 2, lock 3, they correspond to the address of the mutex variable lock 1< lock 2< Lock 3, then all the threads need to obtain 2 or 3 locks at the same time should be in lock 1, lock 2, lock 3 order obtained. If it is difficult to determine a sequence for all locks, you should try to use the Pthread_mutex_trylock call instead of the Pthread_mutex_lock call to avoid deadlocks.


2. Related functions:

(1). static Assignment (global variable/static variable):

pthread_mutex_t Mutex = Pthread_mutex_initializer

Function: Defines a global or static mutex.

(2). pthread_mutex_init function: int pthread_mutex_init (pthread_mutex_t *restrict Mutex,

Const pthrad_mutexattr_t *restrict attr)

attr parameter: The mutex is initialized, generally null, indicating the lack of provincial properties.

Return value: Successful return 0, Failure returns error number.

(3). Pthread_mutex_destroy function: int pthread_mutex_destory (pthread_mutex_t *mutex)

function function: Destroys a mutex.

Return value: Successful return 0, Failure returns error number.

(4). pthread_mutex_lock function: int pthread_mutex_lock (pthread_mutex_t *mutex)

function function: Get a lock. (Block type)

Return value: Successful return 0, Failure returns error number.

(5). pthread_mutex_unlock function: int pthread_mutex_unlock (pthread_mutex_t *mutex)

function function: Release a lock.

Return value: Successful return 0, Failure returns error number.

(6). pthread_mutex_trylock function: int pthread_mutex_trylock (pthread_mutex_t *mutex)

function function: Get a lock. (Non-blocking)

Return value: Successful return of 0, if the mutex has already been obtained by another thread, it will return ebusy immediately.


PS: In which the mutex is the key, locking in an appropriate location can improve the sharing of threads. Because the mutex is equivalent to a thread that has exclusive critical resources, the thread emphasizes sharing, so it should be locked at critical critical resources.


3. Related code:

(1). No lock-in conditions:

 1  #include <stdio.h>  2  #include <stdlib.h>  3  #include < pthread.h>  4   5 const int count = 5000;                                                                                                                                                  6 static int g_count = 0;  7    8 void* create_thread (void *ptr)   9 { 10      pthread_detach (Pthread_self ());  11     int tem = 0; 12      int i = 0; 13     for (;i <  count; i++)  14     { 15          tem = g_count; 16         printf ("thread id is:%ul  g_count is:%d\n",  (Unsigned long) pthread_self (),  g _count); 17         g_count = tem + 1;  18     } 19     return null; 20 }  21  22   23 int main ()  24 { 25     pthread_t tid1;  26     pthread_t tid2; 27     pthread_create (& Tid1, null, create_thread, null);  28     pthread_create (&tid2 ,  null, create_thread, null);  29     sleep (1); 30   31     printf ("end is:%d\n",  g_count); 32      return 0; 33 }

Execution Result:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/7F/39/wKioL1cXNVewUBpcAABKp-nPdTg675.png "title=" 2016-04-20 15:45:31 screen. png "alt=" Wkiol1cxnvewubpcaabkp-npdtg675.png "/>

Figure A

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/7F/39/wKioL1cXNXew4H43AABCYWU1rwQ585.png "title=" 2016-04-20 15:47:26 screen. png "alt=" Wkiol1cxnxew4h43aabcywu1rwq585.png "/>

Figure II

If you call thread 1 and thread 2 in the normal order, the end result should be 10000, but you can see from diagram one that the thread is switched, and two threads are accessing the critical resource at the same time.

(2). The case of mutex lock:

Related code:

  1  #include <stdio.h>  2  #include <stdlib.h>  3 # include<pthread.h>  4   5 const int count = 5000;   6 static int g_count = 0;  7 pthread_mutex_t mutex_ Lock =  pthread_mutex_initializer;  8   9 void* create_ Thread (void *ptr)  10 { 11     pthread_detach (Pthread_self ());  12     int tem = 0; 13     int  i = 0; 14     for (; i < count; i++)  15      { 16         pthread_mutex_ Lock (&mutex_lock); 17         tem = g_count;  18         printf ("thread id is:%ul  g_count is:%d\n",  (unsigned  Long) pthread_self (),  g_count); 19         g_count  = tem + 1; 20         pthread_mutex_unlock ( &mutex_lock);  21     } 22     return null ;  23 } 24  25  26 int main ()  27 { 28      pthread_t tid1; 29     pthread_t tid2; 30      pthread_create (&tid1, null, create_thread, null); 31      pthread_create (&tid2, null, create_thread, null); 32      sleep (1);  33  34     printf ("end is:%d\n" ,  g_count);  35&Nbsp;    pthread_mutex_destroy (&mutex_lock); 36      return 0; 37 }

Execution Result:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/7F/39/wKioL1cXPGXS15VWAAA8DLEbrZw181.png "title=" 2016-04-20 16:18:15 screen. png "alt=" Wkiol1cxpgxs15vwaaa8dlebrzw181.png "/>

Figure A

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/7F/39/wKioL1cXPIzS2gYDAAA93oEdJzA688.png "title=" 2016-04-20 16:17:43 screen. png "alt=" Wkiol1cxpizs2gydaaa93oedjza688.png "/>

Figure II

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7F/3C/wKiom1cXO_GSpXWRAAA2IGBcwhQ208.png "title=" 2016-04-20 16:18:28 screen. png "alt=" Wkiom1cxo_gspxwraaa2igbcwhq208.png "/>

Might

As you can see from figure I and figure II, two threads are not conflicting access critical resources.


This article is from "Narcissus" blog, please make sure to keep this source http://10704527.blog.51cto.com/10694527/1765837

Thread separation and thread mutex

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.