我正在学习多线程。关于
http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html#SCHEDULING
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
#define COUNT_DONE 10
#define COUNT_HALT1 3
#define COUNT_HALT2 6
main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, NULL, &functionCount1, NULL);
pthread_create( &thread2, NULL, &functionCount2, NULL);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Final count: %d\n",count);
exit(0);
}
// Write numbers 1-3 and 8-10 as permitted by functionCount2()
void *functionCount1()
{
for(;;)
{
// Lock mutex and then wait for signal to relase mutex
pthread_mutex_lock( &count_mutex );
// Wait while functionCount2() operates on count
// mutex unlocked if condition varialbe in functionCount2() signaled.
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount1: %d\n",count);
pthread_mutex_unlock( &count_mutex );
if(count >= COUNT_DONE) return(NULL);
}
}
// Write numbers 4-7
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
if( count < COUNT_HALT1 || count > COUNT_HALT2 )
{
// Condition of if statement has been met.
// Signal to free waiting thread by freeing the mutex.
// Note: functionCount1() is now permitted to modify "count".
pthread_cond_signal( &condition_var );
}
else
{
count++;
printf("Counter value functionCount2: %d\n",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= COUNT_DONE) return(NULL);
}
}
我想知道代码的控制流程。
作为pthread_cond_wait - unlocks the mutex and waits for the condition variable cond to be signaled
我对流量控制的理解是
1)创建线程一,线程二,并通过线程1控制(考虑单核处理器系统)
2)当它pthread_cond_wait( &condition_var, &count_mutex );
在thread1
例程中遇到时void *functionCount1()
- 它释放锁并进入等待状态,将控制权传递给thread2 void *functionCount1()
3)检查thread2
变量count
,因为它满足count < COUNT_HALT1 || count > COUNT_HALT2
- 它发出信号thread1
并重新启动是递增count
4)重复Steps 2 to 3
显示1-3
thread1
5)因为thread2在行动,和count 4-7
之间没有切换thread1
thread2
6) For count 8-10
againsteps 2-3
被重复。
我想知道我的理解是否正确?是否thread1
进入睡眠并将thread2
其唤醒(即线程已切换)count value 1-3 and 8-10
i.e switching between threads happen 5 times
?
编辑
我要问这个问题的主要关注点是知道它是否会在遇到时thread1
进入状态并且不会再次出现,除非发出信号,然后才会递增,即它不会一次性递增,而是每次递增,它必须等待只有这样的信号才能继续进行sleep
pthread_cond_wait( &condition_var, &count_mutex );
active
thread2
count
1-3
thread2