How pthread lock mutex?

Dec 28, 2011 at 9:07pm
The following code is from http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html#CREATIONTERMINATION

My question is: how can thread2 pass line 57 and execute line 64 if the mutex has been locked by thread1 in line 37. It seems to be a dead cycle to me!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
01	#include <stdio.h>
02	#include <stdlib.h>
03	#include <pthread.h>
04	 
05	pthread_mutex_t count_mutex     = PTHREAD_MUTEX_INITIALIZER;
06	pthread_cond_t  condition_var   = PTHREAD_COND_INITIALIZER;
07	 
08	void *functionCount1();
09	void *functionCount2();
10	int  count = 0;
11	#define COUNT_DONE  10
12	#define COUNT_HALT1  3
13	#define COUNT_HALT2  6
14	 
15	main()
16	{
17	   pthread_t thread1, thread2;
18	 
19	   pthread_create( &thread1, NULL, &functionCount1, NULL);
20	   pthread_create( &thread2, NULL, &functionCount2, NULL);
21	 
22	   pthread_join( thread1, NULL);
23	   pthread_join( thread2, NULL);
24	 
25	   printf("Final count: %d\n",count);
26	 
27	   exit(0);
28	}
29	 
30	// Write numbers 1-3 and 8-10 as permitted by functionCount2()
31	 
32	void *functionCount1()
33	{
34	   for(;;)
35	   {
36	      // Lock mutex and then wait for signal to relase mutex
37	      pthread_mutex_lock( &count_mutex );
38	 
39	      // Wait while functionCount2() operates on count
40	      // mutex unlocked if condition varialbe in functionCount2() signaled.
41	      pthread_cond_wait( &condition_var, &count_mutex );
42	      count++;
43	      printf("Counter value functionCount1: %d\n",count);
44	 
45	      pthread_mutex_unlock( &count_mutex );
46	 
47	      if(count >= COUNT_DONE) return(NULL);
48	    }
49	}
50	 
51	// Write numbers 4-7
52	 
53	void *functionCount2()
54	{
55	    for(;;)
56	    {
57	       pthread_mutex_lock( &count_mutex );
58	 
59	       if( count < COUNT_HALT1 || count > COUNT_HALT2 )
60	       {
61	          // Condition of if statement has been met.
62	          // Signal to free waiting thread by freeing the mutex.
63	          // Note: functionCount1() is now permitted to modify "count".
64	          pthread_cond_signal( &condition_var );
65	       }
66	       else
67	       {
68	          count++;
69	          printf("Counter value functionCount2: %d\n",count);
70	       }
71	 
72	       pthread_mutex_unlock( &count_mutex );
73	 
74	       if(count >= COUNT_DONE) return(NULL);
75	    }
76	 
77	}
Dec 28, 2011 at 11:12pm
thread 1 at line 41 (pthread_cond_wait) unlocks the mutex locked in line 37 (and retakes it when the signal arrives).

pthread_cond_wait POSIX documentation: http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html

Dec 29, 2011 at 3:21pm
That explains. Thank you!
Topic archived. No new replies allowed.