Linux中pthread_create怎么使用
在Linux中,pthread_create函数用于创建一个新的线程。其语法如下:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
其中,参数含义如下:
thread
:用于存储新线程的ID。attr
:线程属性,一般设置为NULL。start_routine
:线程的入口函数,即新线程运行的起始地址。arg
:传递给start_routine函数的参数。下面是一个简单的例子,展示如何使用pthread_create函数创建一个新的线程:
#include <stdio.h>#include <pthread.h>void *myThread(void *arg) {int *num = (int *)arg;printf("Thread ID: %ld, Number: %d\n", pthread_self(), *num);return NULL;}int main() {pthread_t tid;int number = 10;pthread_create(&tid, NULL, myThread, &number);pthread_join(tid, NULL);return 0;}
在上面的例子中,首先定义了一个名为myThread的线程函数,然后在主函数main中使用pthread_create函数创建一个新的线程,并传递参数number给新线程。最后,使用pthread_join函数等待新线程执行完毕。
需要注意的是,使用pthread_create函数创建新线程时,需要链接pthread库。可以使用如下命令编译程序:
gcc -o myprogram myprogram.c -lpthread
下一篇:docker容器之间怎么通信
Linux
webacc.exe是什么文件?webacc.exe是不是病毒
WINSYS.vbs是什么文件?WINSYS.vbs是不是病毒
winssh.exe是什么文件?winssh.exe是不是病毒
wt.exe是什么文件?wt.exe是不是病毒
winsysetm.exe是什么文件?winsysetm.exe是不是病毒
winstrve.exe是什么文件?winstrve.exe是不是病毒
winsysupd7.exe是什么文件?winsysupd7.exe是不是病毒
winsysupd.exe是什么文件?winsysupd.exe是不是病毒
winsysupd2.exe是什么文件?winsysupd2.exe是不是病毒
winsysupd8.exe是什么文件?winsysupd8.exe是不是病毒