多线程函数实例解析

来源:互联网 发布:unity3d入门文章 编辑:程序博客网 时间:2024/05/16 16:09

创建线程,并可以向创建的线程传递一个参数

#include <pthread.h>  int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)  
等待线程终止,并且可以获得线程的返回值;

#include <pthread.h>  int pthread_join(pthread_t thread, void **retval)  
获得线程自身的线程ID;

#include <pthread.h>  pthread_t pthread_self(void);  

线程可以通过下面三种方式退出:

1.线程只是从启动例程中返回,返回值是线程的退出码;
2.线程可以被同一进程中的其它线程取消;
3.线程调用pthread_exit

终止线程,并可以向主线程返回值;

#include <pthread.h>  void pthread_exit(void *retval);  
在创建的线程中调用该函数,使该线程脱离进程(这里的脱离并不是真正意义上的完全脱离;脱离之后,该线程仍然在该进程空间里运行,只不过是当该线程退出的时候,它的资源会自动释放,进程不用等待其并释放其资源;

#include <pthread.h>  int pthread_detach(pthread_t thread);  

综述:

1:如何创建一个或多个线程;

2:如何在主线程中等待刚才创建的线程;

3:如何获得线程的线程ID;

4:如何在向创建的线程传递信息;

5:如何在创建的线程中退出的时候向主线程传递信息;

6:如何使线程脱离主线程;


实例1:简单的创建两个线程,并在主线程中等待这两个线程,使用pthread_create, pthread_join, pthread_self

#include <stdio.h>#include <unistd.h>#include <pthread.h>#include <stdlib.h>//线程入口函数void *threadA(void *arg1){printf("I am thread1, and my thread is %ld\n", pthread_self());sleep(2);printf("thread1 exit, good bye\n");}void *threadB(void *arg2){printf("I am thread2, and my thread is %ld\n", pthread_self());sleep(2);printf("thread2 exit, good bye\n");}int main(){pthread_t thread1, thread2;int res;res = pthread_create(&thread1, NULL, threadA, NULL);if (res != 0){printf("pthread_create1 error.\n");exit(-1);}res = pthread_create(&thread2, NULL, threadB, NULL);if (res != 0){printf("pthread_create2 error.\n");exit(-1);}res = pthread_join(thread1, NULL);if (res != 0){printf("pthread_join1 error.\n");exit(-1);}res = pthread_join(thread2, NULL);if (res != 0){printf("pthread_join2 error.\n");exit(-1);}printf("I am main, my thread exit.\n");exit(0);}

实例2:创建多个线程(个数自己指定),并在主线程中等待这些线程,使用pthread_create, pthread_join, pthread_self

#include <stdio.h>#include <unistd.h>#include <pthread.h>#include <stdlib.h>//线程入口函数void *threadA(void *arg1){printf("I am thread, and my threadId is %ld\n", pthread_self());sleep(2);printf("thread exit, good bye! my Id is %ld\n", pthread_self());}int main(int argc, char *argv[]){//pthread_t thread1, thread2;int res;int i = 0;if (argc != 2){printf("input the number of  thread you want to create:\n");exit(-1);}int thread_num = atoi(argv[1]);pthread_t threadId[thread_num];for (i = 0; i < thread_num; i++){res = pthread_create(&threadId[i], NULL, threadA, NULL);if (res != 0){printf("pthread_create error.\n");exit(-1);}}for (i = 0; i < thread_num; i++){res = pthread_join(threadId[i],NULL);if (res != 0){printf("pthread_join error.\n");exit(-1);}}printf("I am main, my thread exit.\n");exit(0);}









原创粉丝点击