新聞中心

EEPW首頁(yè) > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > 多線程編程之:Linux線程編程

多線程編程之:Linux線程編程

作者: 時(shí)間:2013-09-13 來(lái)源:網(wǎng)絡(luò) 收藏


本文引用地址:http://m.butianyuan.cn/article/257101.htm

(3)使用實(shí)例。

下面的實(shí)例是在9.2.1小節(jié)示例代碼的基礎(chǔ)上增加互斥鎖功能,實(shí)現(xiàn)原本獨(dú)立與無(wú)序的多個(gè)線程能夠按順序執(zhí)行。


/*thread_mutex.c*/

#include stdio.h>

#include stdlib.h>

#include pthread.h>


#define THREAD_NUMBER 3 /* 線程數(shù) */

#define REPEAT_NUMBER 3 /* 每個(gè)線程的小任務(wù)數(shù) */

#define DELAY_TIME_LEVELS 10.0 /*小任務(wù)之間的最大時(shí)間間隔*/

pthread_mutex_t mutex;


void *thrd_func(void *arg)

{

int thrd_num = (int)arg;

int delay_time = 0, count = 0;

int res;

/* 互斥鎖上鎖 */

res = pthread_mutex_lock(mutex);

if (res)

{

printf(Thread %d lock failedn, thrd_num);

pthread_exit(NULL);

}

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

/* 互斥鎖初始化 */

pthread_mutex_init(mutex, NULL);

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

{

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

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

{

res = pthread_join(thread[no], thrd_ret);

if (!res)

{

printf(Thread %d joinedn, no);

}

else

{

printf(Thread %d join failedn, no);

}

/* 互斥鎖解鎖 */

pthread_mutex_unlock(mutex);

}

pthread_mutex_destroy(mutex);

return 0;

}


該實(shí)例的運(yùn)行結(jié)果如下所示。這里3個(gè)線程之間的運(yùn)行順序跟創(chuàng)建線程的順序相同。



$ ./thread_mutex

Create treads success

Waiting for threads to finish...

Thread 0 is starting

Thread 0: job 0 delay = 7

Thread 0: job 1 delay = 7

Thread 0: job 2 delay = 6

Thread 0 finished

Thread 0 joined

Thread 1 is starting

Thread 1: job 0 delay = 3

Thread 1: job 1 delay = 5

Thread 1: job 2 delay = 10

Thread 1 finished

Thread 1 joined

Thread 2 is starting

Thread 2: job 0 delay = 6

Thread 2: job 1 delay = 10

Thread 2: job 2 delay = 8

Thread 2 finished

Thread 2 joined

linux操作系統(tǒng)文章專題:linux操作系統(tǒng)詳解(linux不再難懂)

linux相關(guān)文章:linux教程




評(píng)論


相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉