对于一般的单线程的程序都是按照一定的顺序执行的,如果在主线程里面创建线程,程序就会在创建线程的地方产生分支,变成两个程序执行。这似乎和多进程一样,其实不然,子进程是通过拷贝父进程的地址空间来实现的;而线程与进程内的线程共享程序代码,一般代码可以同时被多个线程执行。
线程的创建通过函数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.前者表示系统限制创建新的线程,例如:线程数目过多;后者表示第二个参数代表的线程属性值非法。线程创建成功后,新创建的线程开始运行第3个参数锁指向的函数,原来的线程继续运行。
下面是个简单的例子
/*createthread.c*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
int * thread(void * arg)
{
pthread_t newthid;
newthid=pthread_self(); //pthread_self()函数返回调用线程的Id。
printf("this is a new thread,thread ID=%u\n",newthid);
return NULL;
}
int main(void )
{
pthread_t thid;
printf("main thread,ID is %u\n",pthread_self());
if(pthread_create(&thid,NULL,(void *)thread,NULL)!=0) //创建线程。
{
printf("thread creation failed\n");
exit(1);
}
sleep(1); //暂停1秒
exit(0);
}
编译运行:-----------
[root@wuzhq thread]# gcc -o createthread createthread.c -lpthread(这块的-lpthread一定不能忘记)
[root@wuzhq thread]# ls
createthread simple1 th_ex thread_example.c
createthread.c simple1.c th_pool thread_pool.c
[root@wuzhq thread]# ./createthread
main thread,ID is 3086227136
this is a new thread,thread ID=3086224272