- 论坛徽章:
- 0
|
本人新手,向各位牛人求教!
以下实例中创建3个线程,为了更好的描述线程间的并行执行,让3个线程重用一个执行函数。每个线程都有五次循环(可以看成5个小任务),每次循环之间会随机等待1~10s的时间。- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #define THREAD_NUMBER 3 /* 线程数*/
- #define REPEAT_NUMBER 3 /* 每个线程中的小任务数*/
- #define DELAY_TIME_LEVELS 10.0 /* 小任务间的最大时间间隔*/
- /*声明一个全局锁*/
- pthread_mutex_t mutex;
- /*线程函数例程*/
- void *thrd_func(void *arg)
- {
- int thrd_num = (int)arg;
- int delay_time = 0;
- int res = 0;
- int count = 0;
- /*互斥锁上锁*/
- res = pthread_mutex_lock(&mutex);
- if(res)
- {
- printf("Thread %d Lock failed!\n",thrd_num);
- pthread_exit(NULL);
- }
- 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 is finished\n",thrd_num);
- pthread_exit(NULL);
- }
- int main(void)
- {
- int loop = 0;
- int res = 0;
-
- void *thrd_res = NULL;
-
- pthread_t thread[THREAD_NUMBER] = {0};
- srand(time(NULL));
- /*互斥锁初始化*/
- pthread_mutex_init(&mutex,NULL);
- for(loop = 0; loop < THREAD_NUMBER; loop++)
- {
- /* 创建多线程*/
- res = pthread_create(&thread[loop],NULL,thrd_func,(void*)loop);
-
- if(0 != res)
- {
- printf("Create thread %d fail!\n",loop);
- exit(res);
- }
- }
- printf("Create threads success!\nWaiting for threads to finish......\n");
- for(loop = 0; loop < THREAD_NUMBER; loop++)
- {
- /* 等待多线程结束*/
- res = pthread_join(thread[loop],&thrd_res);
-
- if(!res)
- {
- printf("Thread %d joined!\n",loop);
- }
- else
- {
- printf("Thread %d join failed!\n",loop);
- }
- /*互斥锁解锁*/
- pthread_mutex_unlock(&mutex);
- }
- /*消除互斥锁*/
- pthread_mutex_destroy(&mutex);
- return 0;
- }
复制代码 但是运行下来是以下情况:
[root@chengxiaoquan pthread_mutex]# gcc pthread_mutex.c -o pthread_mutex -lpthread
[root@chengxiaoquan pthread_mutex]# ./pthread_mutex
Create threads success!
Waiting for threads to finish......
Thread 2 is Starting!
Thread2: job 0 delay = 8
Thread2: job 1 delay = 4
Thread2: job 2 delay = 3
Thread 2 is finished
运行到这里就不动了!!!
怎么只有线程2????而且pthread2并没有join,为什么呢?本人新手,向各位牛人求教! |
|