linux有创建线程的函数,即“pthread_create()”函数。该函数是类Unix操作系统中创建线程的函数,支持四个参数:参数1是指向线程标识符的指针、参数2用来设置线程属性、参数3是线程运行函数的起始地址、参数4是运行函数的参数。
本教程操作环境:linux5.9.8系统、Dell G3电脑。
linux有创建线程的函数,那就是pthread_create()函数。
pthread_create()是类Unix操作系统(Unix、Linux、Mac OS X等)中创建线程的函数
头文件
#include
函数声明
int pthread_create( pthread_t *restrict tidp, //新创建的线程ID指向的内存单元。 const pthread_attr_t *restrict attr, //线程属性,默认为NULL void *(*start_rtn)(void *), //新创建的线程从start_rtn函数的地址开始运行 void *restrict arg //默认为NULL。上述函数需要参数,将参数放入结构中并将地址作为arg传入。 );
返回值
-
若成功则返回0,否则返回出错编号
参数
-
第一个参数为指向线程标识符的指针。
-
第二个参数用来设置线程属性。
-
第三个参数是线程运行函数的地址。
-
最后一个参数是运行函数的参数。
注意
在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库。
函数用法
#include <stdio.h> #include <string.h> #include <iostream> #include <pthread.h> #include <unistd.h> #include <vector> #include "main.h" using namespace std; struct Sample { uint32_t index; char sex; uint32_t age; uint32_t result; }; void* TaskEntry(void *args) { Sample *sa = (Sample*)args; uint32_t num = sa->index; if (num == 0) { printf("TaskEntry entry num = 0n"); // 线程1执行体 sleep(10); printf("TaskEntry entry num = 0 is over!!!n"); } else if (num == 1) { printf("TaskEntry entry num = 1n"); // 线程2执行体 sleep(10); printf("TaskEntry entry num = 1 is over!!!n"); } else if (num == 2) { printf("TaskEntry entry num = 2n"); // 线程3执行体 sleep(2); printf("TaskEntry entry num = 2 is over!!!n"); } } uint32_t CreateTask(pthread_t& pid, Sample& sample) { // 假设Sample.index == 2创建任务失败,直接返回 if (sample.index == 2) { return 2; } pthread_attr_t attr; // 设置线程属性 pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 64 * 1024); // 设置线程栈大小为64KB uint32_t ret = pthread_create(&pid, &attr, (void*(*)(void*))TaskEntry, (void*)&sample); if (ret != 0) { return ret; } pthread_attr_destroy(&attr); // 取消线程的设置属性 return 0; } void VerifyTask(vector<pthread_t>& taskID, vector<sample>& taskArgs) { void *ret; for (int index = 0; index taskID(3); vector<sample> taskArgs(3); for (int i = 0; i <p id="注意编译的使用需要加上编译选项-lpthread比如g--lpthread-maincpp--o-main">注意编译的使用需要加上编译选项-lpthread,比如:g++ -lpthread main.cpp -o main</p> <p>相关推荐:《<a href="http://www.php.cn/course/list/33.html" target="_blank">Linux视频教程</a>》</p></sample></sample></pthread_t></vector></unistd.h></pthread.h></iostream></string.h></stdio.h>
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END