新闻中心

EEPW首页>嵌入式系统>设计应用> 多线程编程之:Linux线程编程

多线程编程之:Linux线程编程

作者: 时间:2013-09-13 来源:网络 收藏


本文引用地址://m.amcfsurvey.com/article/257101.htm

(4)使用实例。

在前面已经通过互斥锁同步机制实现了多线程的顺序执行。下面的例子是用信号量同步机制实现3个线程之间的有序执行,只是执行顺序是跟创建线程的顺序相反。


/*thread_sem.c*/

#include stdio.h>

#include stdlib.h>

#include pthread.h>

#include semaphore.h>


#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;

/* 进行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 =(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);

/* 对最后创建的线程的信号量进行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);

}

/* 进行V操作 */

sem_post(sem[(no + THREAD_NUMBER - 1) % THREAD_NUMBER]);

}


for (no = 0; no THREAD_NUMBER; no++)

{

/* 删除信号量 */

sem_destroy(sem[no]);

}


return 0;

}

linux操作系统文章专题:linux操作系统详解(linux不再难懂)

linux相关文章:linux教程




评论


相关推荐

技术专区

关闭