多线程模板

Linux多线程程序:

用到的函数:

int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*func) (void *), void *arg);

pthread_create用于创建一个线程,成功返回0,否则返回Exxx(为正数)。

pthread_t tid:线程id的类型为pthread_t,通常为无符号整型,当调用pthread_create成功时,通过tid指针返回。
const pthread_attr_t *attr:指定创建线程的属性,如线程优先级、初始栈大小、是否为守护进程等。可以使用NULL来使用默认值,通常情况下我们都是使用默认值。
void *(*func) (void *):函数指针func,指定当新的线程创建之后,将执行的函数。
void *arg:线程将执行的函数的参数。如果想传递多个参数,请将它们封装在一个结构体中。

int pthread_join(pthread_t thread, void **retval);
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <unistd.h> void *fun_1(void *arg)//线程1 { char *p = (char *)arg; while(1){ puts(p); sleep(1); } } void *fun_2(void *arg)//线程2 { char *p = (char *)arg; while(1){ puts(p); sleep(1); } } int main()//main函数内为主线程,主线程在运行子线程才能正常运行。 { pthread_t tid_1; pthread_t tid_2; if(0 != pthread_create(&tid_1, NULL, fun_1, "hello world!"))//将hello word!传给子函数的arg { perror("pthread_create1"); return -1; } if(0 != pthread_create(&tid_2, NULL, fun_2, "hi word!"))//将hi word!传给子函数的arg { perror("pthread_create2"); return -1; } pthread_join(tid_1,NULL); pthread_join(tid_2,NULL); }

注意:多线程程序在编译的时候需要链接对应的库-lpthread


__EOF__

本文作者西北小蚂蚁
本文链接https://www.cnblogs.com/JinShanCheShen/p/16077013.html
关于博主:山不向我走来,我便向他走去!
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   西北小蚂蚁  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示