#include <stdio.h>
#include <pthread.h>
void thread(void) {
int i;
printf("This is a thread.\n");
pthread_exit(NULL);
}
int main(void) {
pthread_t id;
int ret;
ret = pthread_create(&id, NULL, (void *)thread, NULL);
if(ret != 0) {
printf("Create pthread error!\n");
exit(1);
}
int i;
printf("This is the main process.\n");
pthread_join(id, NULL);
return 0;
}
函数说明:
int pthread_create(pthread_t*restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);
此函数接受四个参数,分别为指向线程标识符的指针、线程属性、线程运行函数的起始地址、运行函数的参数。第二个和第四个参数暂时都为NULL,以后也许会修改。
若此函数执行成功,则返回0,否则返回错误编号。
pthread_t用于声明线程id。
int pthread_join(pthread_t thread, void **retval);
此函数以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果进程已经结束,那么该函数会立即返回。在这里的意思是主函数在等待线程都结束后才退出,如果不加这个函数的话,主函数执行完自己的代码程序就终止了,不在乎线程是否也执行结束。
第一个参数为线程ID,标识唯一线程。第二个参数为用户定义的指针,用来存储被等待线程的返回值。
若此函数执行成功,则返回0。否则返回错误编号。
注:编译时要加上-lpthread,如果允许使用gdb调试的话,还要加上-g
gcc -o homework1 homework1.c -lpthread