<pthread.h>头文件中,语法格式如下:
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine) (void *),
void *arg);
各个参数的含义是:<pthread.h>头文件中,此类型的变量专门表示线程的属性。关于线程属性,您可以阅读《线程属性有哪些,如何自定义线程属性?》一文做详细地了解。4) void *arg:指定传递给 start_routine 函数的实参,当不需要传递任何数据时,将 arg 赋值为 NULL 即可。如果该函数有返回值,则线程执行完函数后,函数的返回值可以由 pthread_join() 函数接收。有关 phtread_join() 函数的用法,我们会在《获取线程函数返回值》一节给大家做详细讲解。
接下来通过一个样例,给大家演示 pthread_create() 函数的用法:以上这些宏都声明在 <errno.h> 头文件中,如果程序中想使用这些宏,需提前引入此头文件。
#include <stdio.h>
#include <unistd.h> //调用 sleep() 函数
#include <pthread.h> //调用 pthread_create() 函数
void *ThreadFun(void *arg)
{
if (arg == NULL) {
printf("arg is NULL\n");
}
else {
printf("%s\n", (char*)arg);
}
return NULL;
}
int main()
{
int res;
char * url = "http://c.biancheng.net";
//定义两个表示线程的变量(标识符)
pthread_t myThread1,myThread2;
//创建 myThread1 线程
res = pthread_create(&myThread1, NULL, ThreadFun, NULL);
if (res != 0) {
printf("线程创建失败");
return 0;
}
sleep(5); //令主线程等到 myThread1 线程执行完成
//创建 myThread2 线程
res = pthread_create(&myThread2, NULL, ThreadFun,(void*)url);
if (res != 0) {
printf("线程创建失败");
return 0;
}
sleep(5); // 令主线程等到 mythread2 线程执行完成
return 0;
}
假设程序编写在 thread.c 文件中,执行过程如下:
[root@localhost ~]# gcc thread.c -o thread.exe -lpthread
[root@localhost ~]# ./thread.exe
arg is NULL
http://c.biancheng.net
您可以尝试将程序中的 sleep() 函数全部注释掉,然后重新编译、执行此程序。整个进程会随着主线程执行结束而立即终止,由于主线程执行太快,子线程可能尚未执行完就被强制终止。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有