1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C语言多线程编程之一

C语言多线程编程之一

时间:2022-12-26 15:08:50

相关推荐

C语言多线程编程之一

在C语言中可以使用pthread.h的API来创建线程,pthread.h符合POSIX标准,意味可以在Unix和Linux下运行,Windows NT也提供了相应的支持

创建多线程:

#include<stdio.h>#include<pthread.h>void *thread_func(void *args){printf("This is thread_func");return 0;}int main(){pthread_t thread;if(pthread_create(&thread,NULL,thread_func,NULL)){printf("creat thread fail\n");}else{printf("creat thread successfull\n"); }pthread_exit(NULL);}

关于pthread_create函数,成功的时候返回的为0,失败的时候返回的是1

第一个参数为指向线程标识符的指针

第二个参数为线程属性

第三个参数为函数的起始地址

第四个参数为运行函数的参数,利用第四个参数可以在创建线程的时候向函数中传入参数

向创建的线程中传入参数:

#include<stdio.h>#include<pthread.h>void *thread_func(void *parameter){printf("This is thread_func,parameter:%s",parameter);return 0;}int main(){pthread_t thread;char* parameter="ok";if(pthread_create(&thread,NULL,thread_func,(void *)parameter)){printf("creat thread fail\n");}else{printf("creat thread successfull\n"); }pthread_exit(NULL);}

创建线程池(创建时候传入参数):

#include<stdio.h>#include<pthread.h>#define THREAD_NUM 5void *thread_func(void *parameter){printf("This is thread_func,parameter:%d\n",parameter);return 0;}int main(){pthread_t threads[THREAD_NUM];for(int i=0;i<THREAD_NUM;i++){if(pthread_create(&threads[i],NULL,thread_func,(void*)i)){printf("creat thread fail\n");}else{printf("creat thread successfull\n"); }}pthread_exit(NULL);}

pthread_join()和pthread_detach()

如果不使用上面的两个关键字,主线程结束的时候也会结束分线程,但是主线程一直不结束的时候,分线程分配的内存也不会不回收

使用pthread_join()关键字,是主线程和分线程连接上,等线程执行完成以后,就会回收分线程内存,继续主线程

其有两个参数,第一个参数为线程,第二个参数为线程的返回值

#include <pthread.h>#include <stdlib.h>#include <stdio.h>void *thread_function(void *arg) {int i;for ( i=0; i<8; i++) {printf("Thread working...! %d \n",i);sleep(1);}return NULL;}int main(void) {pthread_t mythread;if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {printf("error creating thread.");abort();}pthread_join ( mythread, NULL ) ;printf("thread done! \n");}

使用pthread_detach()关键字,将线程分离出去,主线程和分线程各跑各个的,互不相干,分线程结束后会自动回收内存

其有一个参数,参数为线程

#include <pthread.h>#include <stdlib.h>#include <stdio.h>void *thread_function(void *arg) {int i;for ( i=0; i<8; i++) {printf("Thread working...! %d \n",i);sleep(1);}return NULL;}int main(void) {pthread_t mythread;if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {printf("error creating thread.");abort();}pthread_detach ( mythread) ;printf("thread done! \n");}

退出pthread_exit

pthread_exit (status)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。