多線程編程之:Linux線程編程
(4)使用實(shí)例。
在前面已經(jīng)通過互斥鎖同步機(jī)制實(shí)現(xiàn)了多線程的順序執(zhí)行。下面的例子是用信號量同步機(jī)制實(shí)現(xiàn)3個(gè)線程之間的有序執(zhí)行,只是執(zhí)行順序是跟創(chuàng)建線程的順序相反。
/*thread_sem.c*/
#include stdio.h>
#include stdlib.h>
#include pthread.h>
#include semaphore.h>
#define THREAD_NUMBER 3 /* 線程數(shù) */
#define REPEAT_NUMBER 3 /* 每個(gè)線程中的小任務(wù)數(shù) */
#define DELAY_TIME_LEVELS 10.0 /*小任務(wù)之間的最大時(shí)間間隔*/
sem_t sem[THREAD_NUMBER];
void *thrd_func(void *arg)
{
int thrd_num = (int)arg;
int delay_time = 0;
int count = 0;
/* 進(jìn)行P操作 */
sem_wait(sem[thrd_num]);
printf(Thread %d is startingn, 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 = %dn,
thrd_num, count, delay_time);
}
printf(Thread %d finishedn, thrd_num);
pthread_exit(NULL);
}
int main(void)
{
pthread_t thread[THREAD_NUMBER];
int no = 0, res;
void * thrd_ret;
srand(time(NULL));
for (no = 0; no THREAD_NUMBER; no++)
{
sem_init(sem[no], 0, 0);
res = pthread_create(thread[no], NULL, thrd_func, (void*)no);
if (res != 0)
{
printf(Create thread %d failedn, no);
exit(res);
}
}
printf(Create treads successn Waiting for threads to finish...n);
/* 對最后創(chuàng)建的線程的信號量進(jìn)行V操作 */
sem_post(sem[THREAD_NUMBER - 1]);
for (no = THREAD_NUMBER - 1; no >= 0; no--)
{
res = pthread_join(thread[no], thrd_ret);
if (!res)
{
printf(Thread %d joinedn, no);
}
else
{
printf(Thread %d join failedn, no);
}
/* 進(jìn)行V操作 */
sem_post(sem[(no + THREAD_NUMBER - 1) % THREAD_NUMBER]);
}
for (no = 0; no THREAD_NUMBER; no++)
{
/* 刪除信號量 */
sem_destroy(sem[no]);
}
return 0;
}
linux操作系統(tǒng)文章專題:linux操作系統(tǒng)詳解(linux不再難懂)linux相關(guān)文章:linux教程
評論