多线程创建

本篇博文,主要是举例如何创建多个线程,以及观察到pthread_join()函数的作用。只是做了一些简单的分析,供初学者学习使用。


#include   
#include   
#include   
#include 

#define NUM 6    //创建线程数量

void *thread_function(void *arg);  

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

    for (index = 0; index < NUM; ++index) {  //循环创建线程
        res = pthread_create(&a_thread[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(a_thread[index], &thread_result);  
        if (res == 0)  
        {  
            printf("Picked up a thread:%d\n", index );  
        }  
        else  
        {  
            perror("pthread_join failed\n");  
        }  
    }  

    printf("All done\n");  

    exit(EXIT_SUCCESS);  
}  

void *thread_function(void *arg)    //主要任务就是sleep随机时间,然后退出
{  
    int my_number = (int)arg;  
    int rand_num;  

    printf("thread_function is running. Argument was %d\n", my_number);  

    srand( (unsigned) time(NULL) );
    rand_num = 1 + (int)(9.0 * rand()/(RAND_MAX + 1.0));  
    printf("%d sleep time is %d\n",my_number,rand_num);
    sleep(rand_num);  
    printf("Bye from %d\n", my_number);  
    pthread_exit(NULL);  
} 

以上代码每次执行的结果都不同,以下贴出一次代码执行的情况来分析。

thread_function is running. Argument was 0
0 sleep time is 4
thread_function is running. Argument was 1
1 sleep time is 8
thread_function is running. Argument was 2
2 sleep time is 6
thread_function is running. Argument was 3
3 sleep time is 1
Bye from 0        //sleep 4s 后返回
Bye from 3        //sleep 1s 后返回
thread_function is running. Argument was 4
4 sleep time is 8
thread_function is running. Argument was 5
5 sleep time is 2
Waiting for threads to finished...
Bye from 5
Picked up a thread:5
Bye from 2
Bye from 1
Bye from 4
Picked up a thread:4    //可以明显看到,主线程阻塞在这里,等待4号线程返回
Picked up a thread:3
Picked up a thread:2
Picked up a thread:1
Picked up a thread:0
All done

你可能感兴趣的:(多线程,线程)