Problems may occur when using conditions (1)

Source: Internet
Author: User

1 # include <stdio. h>
2 # include <stddef. h>
3 # include <pthread. h>
4 # include <unistd. h>
5 Int I = 1;
6 pthread_mutex_t mutex;
7 pthread_cond_t cond;
8
9 void * task1 ()
10 {
11 For (I = 1; I <9; I ++)
12 {
13 pthread_mutex_lock (& mutex );
14 if (I % 3! = 0) printf ("in the task1: % d \ n", I );
15 else pthread_cond_signal (& Cond );
16 pthread_mutex_unlock (& mutex );
17 sleep (1 );
18}
19 return NULL;
20}
21
22 void * task2 ()
23 {
24 while (I <9)
25 {
26 pthread_mutex_lock (& mutex );
27 if (I % 3! = 0)
28 pthread_cond_wait (& cond, & mutex); // The end of Task 2 is always in the wait state because I = 8.
29
30 printf ("in the task2: \ t % d \ n", I );
31 pthread_mutex_unlock (& mutex );
32 sleep (1 );
33}
34 return NULL;
35
36}
37
38
39 int main ()
40 {
41 pthread_t t_id1, t_id2;
42 int succ;
43
44 pthread_mutex_init (& mutex, null );
45 pthread_cond_init (& cond, null );
46
47 succ = pthread_create (& t_id1, null, task1, null );
48 if (succ) {printf ("Failure in create thread! \ N "); return NULL ;}
49
50 succ = pthread_create (& t_id2, null, task2, null );
51 if (succ) {printf ("Failure in create thread2! \ N "); return NULL ;}
52
53 pthread_join (t_id1, null );
54 pthread_join (t_id2, null );
55
56 pthread_mutex_destroy (& mutex );
57 pthread_cond_destroy (& Cond );
58 return NULL;
59}
 

When using pthread_cond_wait (), you need to consider whether the program will exit when it is in the waiting state. When the above program I = 8, it will remain in the waiting state.

Solution 1: When setting conditions, make the process of wait not waiting during the last call;

Solution 2: Use pthread_cond_timedwait ()

 

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.