多线程的创建
pthread_create()函数
在Linux下线程的创建通过函数pthread_create来完成,该函数的声明如下:#include<pthread.h>
int pthread_create(pthread_t *thread, pthread_attr_t *attr, void*(*start_routine)(void*), void *arg);函数各参数含义如下:
thread:该参数是一个指针,档线程创建成功时,用来返回创建的线程ID。
attr:该参数用于指定线程的属性,NULL表示使用默认属性。
start_routine:该参数为一个函数指针,指向线程创建后要调用的函数。这个被线程调用的函数也被称为线程函数。
arg:该参数指向传递给线程函数的参数。
返回:
档线程创建成功时,pthread_create函数返回0,若不为0,则说明创建线程失败。
如果返回EAGAIN,表示系统限制创建新进程,例如新进程数目过多;
如果返回EINVAL,表示第二个参数代表的线程属性值非法。
示例代码:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
int* thread(void*arg)
{
pthread_t newthid;
newthid=pthread_self();//得到本线程ID
printf("this is a new thread,thread ID = %u\n",newthid);
return 0;
}
int main()
{
pthread_t thid;
printf("main thread,ID is %u\n",pthread_self());//打印主线程的ID
if(pthread_create(&thid,NULL,(void*)thread,NULL)!=0)//线程创建成功后,直接调用线程函数,线程函数返回后,才调用下面的sleep.
{
printf("thread creation failed\n");
exit(1);
}
sleep(1);
printf("pthread_createID:%u\n",thid);//检查pthread_create函数返回值
return 0;
}
编译问题:
由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数:
编译:gcc creatthread.c -o creatthread -lpthread
运行结果:
pc@ubuntu:~/linux_lan/thread$ ./creatthread
main thread,ID is 1435363136
this is a new thread,thread ID = 1427052288
pthread_createID:1427052288
pthread_once()函数
在多线程编程中,有些事仅需要执行一次,这种情况下调用pthread_once()函数就可以。
示例如下:
#include<stdio.h>
#include<pthread.h>
pthread_once_t once=PTHREAD_ONCE_INIT;
void run()
{
printf("Fuction run is running in thread %u\n",pthread_self());
}
int* thread1(void* arg)
{
pthread_t thid=pthread_self();
printf("Current thread‘s ID is %u\n",thid);
pthread_once(&once,run);
printf("thread1 ends\n");
return 0;
}
int* thread2(void* arg)
{
pthread_t thid=pthread_self();
printf("Current thread's ID is %u\n",thid);
pthread_once(&once,run);
printf("thread2 ends\n");
return 0;
}
int main()
{
pthread_t thid1,thid2;
pthread_create(&thid1,NULL,(void*)thread1,NULL);
pthread_create(&thid2,NULL,(void*)thread2,NULL);
sleep(3);
printf("main thread exit!\n");
return 0;
}
运行结果:
pc@ubuntu:~/linux_lan/thread$ ./pthread_once
Current thread‘s ID is 724174592
Fuction run is running in thread 724174592
thread1 ends
Current thread's ID is 715781888
thread2 ends
main thread exit!
分析:
该示例中,mian函数创建了两个线程,两个线程函数分别通过pthread_once()调用了同一函数,结果被调用的函数只执行了一次。