linux 下也可以创建线程。
1.要包含库头:#include <pthread.h>
2.编译时: -l pthread
3.创建线程函数:
int pthread_create ( pthread_t *thread,const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
参数说明:
1)thread: 是个类型为pthread_t(unsigned long int)的地址参数,存储线程ID,当线程成功创建后返回线程ID。
2)attr:表示线程属性的地址参数,一般使用时用NULL即可。
3)start_routine:线程函数。值得注意的是此函数定义时要如下定义:
void* threadfunction(void* threadparam)
{
//加入线程运行的代码
return (void*)0;
}
4)arg:表示线程的参数地址。
函数说明:
当线程创建成功此函数返回0,thread存储线程ID。当线程创建失败时,则返回非0的错误代码。
4.线程等待:
int pthread_join(pthread *thread,void **thread_return);
参数说明:
1)thread: 被等待的线程标识符。
2)thread_return : 一个用户定义的指针,它可以用来存储被等待线程的返回值。
函数说明:
这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回 。
一个线程的结束有两种方式:
一种是线程函数自然运行结束,
另一种是 通过函数pthread_exit来实现。它的函数原型为:
linux 下创建线程
最新推荐文章于 2024-05-01 12:39:06 发布