分类: LINUX
2010-07-09 14:45:14
上次用互斥锁,这次用信号量同步机制来实现同步。
系统函数有:sem_init, sem_wait, sem_trywait, sem_post, sem_getvalue, sem_destroy.
源代码来自华清远见:
#include
#include
#include
#include
#define THREAD_NUMBER 3
#define REPEAT_NUMBER 3
#define DELAY_TIME_LEVELS 10.0
sem_t sem[THREAD_NUMBER];
void *thrd_func(void *arg)
{
int thrd_num = (int)arg;
int delay_time = 0;
int count = 0;
sem_wait(&sem[thrd_num]);//P操作
printf("Thread %d is starting\n", thrd_num);
for(count = 0; count < REPEAT_NUMBER; count++)
{
delay_time = (int) (rand() *DELAY_TIME_LEVELS/(RAND_MAX) + 1);
sleep(delay_time);
printf("\tThread %d: job %d delay = %d\n", thrd_num, count, delay_time);
}
printf("Thread %d finished\n", thrd_num);
pthread_exit(NULL);
}
int main()
{
pthread_t thread[THREAD_NUMBER];
int no = 0, res;
void *thrd_ret;
srand(time(NULL));
for(no = 0; no < THREAD_NUMBER; no++)
{
res = pthread_create(&thread[no], NULL, thrd_func, (void*)no);
if(res != 0)
{
printf("Create thread %d failed\n", no);
exit(res);
}
}
printf("Create threads success\nWaiting for threads to finish..\n");
sem_post(&sem[THREAD_NUMBER - 1]);//对最后创建的线程信号量进行V操作
for( no = THREAD_NUMBER - 1; no >= 0; no--)
{
res = pthread_join(thread[no], &thrd_ret);
if(!res)
{
printf("Thread %d joined\n", no);
}
else
{
printf("Thread %d join failed\n", no);
}
sem_post(&sem[(no + THREAD_NUMBER -1) % THREAD_NUMBER]);//V操作
}
for(no = 0; no < THREAD_NUMBER; no++)
{
sem_destroy(&sem[no]);//删除信号量
}
return 0;
}
编译运行,结果如下:
可以看出3个线程运行是与创建的顺序相反的,同样我们用信号量实现了线程的同步。