在linux中,多线程使用如下原型进行创建
int pthread_creat(pthread_t *tidp,const
pthread_addr_t *addr,void *(*start_rtn)(void),void *args);
其中tidp为线程id号;addr为线程属性,通常为空;第三个参数为线程执行的函数指针,第四个参数为线程函数的参数。
若创建成功则返回0,未成功则返回错误号。
在编译时由于该函数所需要的库lpthread.a不是常用的C库,因此需要在编译命令后加上-lpthread。
由于在主进程通常结束的很快,而当主进程结束时其包含的所有线程也都结束了,若不包含其他语句,很容易出现创建的线程来不及执行的情况,因此,我们通常会在主进程中加入sleep()函数或者int pthread_join(pthread_t
thread,void **retval)来进行控制。
sleep自不用说,用于阻塞主进程,使线程得以执行。
pthread_join则是以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果进程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
参数:
thread: 线程标识符,即线程ID,标识唯一线程。
retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 : 0代表成功。失败,返回的则是错误号。
示例:
#include
#include
void *myThread1(void)
{
int i;
for (i=0;
i<100; i++)
{
printf("This is the 1st pthread,created by zieckey.\n");
sleep(1);//Let this thread to sleep 1 second,and then continue to
run
}
}
void *myThread2(void)
{
int i;
for (i=0;
i<100; i++)
{
printf("This is the 2st pthread,created by zieckey.\n");
sleep(1);
}
}
int main()
{
int i=0,
ret=0;
pthread_t
id1,id2;
ret =
pthread_create(&id1, NULL, (void*)myThread1,
NULL);
if
(ret)
{
printf("Create pthread error!\n");
return 1;
}
ret =
pthread_create(&id2, NULL, (void*)myThread2,
NULL);
if
(ret)
{
printf("Create pthread error!\n");
return 1;
}
pthread_join(id1, NULL);
pthread_join(id2, NULL);
return
0;
}