现在的位置: 首页 > 综合 > 正文

Linux 简单多线程

2017年12月26日 ⁄ 综合 ⁄ 共 1266字 ⁄ 字号 评论关闭

#include <iostream>
#include <pthread.h>
using namespace std;

#define NUM 6

void *thread_function(void* arg);

int main()
{
int res, index;
pthread_t
threadID[NUM];
void *thread_result;

for(index = 0; index < NUM; ++index)
{
res = pthread_create(&threadID[index], NULL, thread_function, (void*)&index);
if (res != 0)
{
perror("Thread create failed!");
exit(EXIT_FAILURE);
}
sleep(1);
}

printf("Waiting for threads to finished...\n");

for(index = NUM - 1; index >= 0; --index)
{
res = pthread_join(threadID[index], &thread_result);
if (res != 0)
{
perror("Thread join failed!");
exit(EXIT_FAILURE);
}
else
{
printf("Picked up a thread: %d\n", index+1);
}
}
printf("All done\n");
return(EXIT_SUCCESS);
}

void *thread_function(void *arg)
{
int my_number
= *(int*)arg;
int rand_num;
printf("thread_function is running.argument was %d\n", my_number);
rand_num
= 1 + (int)(9.0 * rand()/(RAND_MAX+1.0));
sleep(rand_num);
printf("Bye from %d\n", my_number);
pthread_exit(NULL);

}

./a.out 
thread_function is running.argument was 0
thread_function is running.argument was 1
thread_function is running.argument was 2
thread_function is running.argument was 3
thread_function is running.argument was 4
Bye from 1
thread_function is running.argument was 5
Waiting for threads to finished...
Bye from 5
Picked up a thread: 6
Bye from 0
Bye from 2
Bye from 3
Bye from 4
Picked up a thread: 5
Picked up a thread: 4
Picked up a thread: 3
Picked up a thread: 2
Picked up a thread: 1
All done

【上篇】
【下篇】

抱歉!评论已关闭.