创建线程
pthread_create( )如果该函数执行成功,线程就自动开始运行了
pthread_join()函数可以用于将当前线程挂起来等待线程的结束。这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源就被收回。
线程入口函数运行完之后,该线程也就退出了,这也是线程退出一种方法(线程自然“死亡”)。另一种退出线程的方法是使用函数pthread_exit(),这是线程的主动行为.
pthread_cancel()函数实现别的线程中要终止另一个线程的执行
简单实例:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
void *thread1_proc(void *arg)
{
int i=0;
while(i<10)
{
printf("thread1:%d\n",i);
fflush(stdout);
sleep(4);
i++;
}
printf("Thread1 finished!\n");
pthread_exit(NULL);
}
void *thread2_proc(void *arg)
{
int i=10;
while(i<20)
{
printf(" thread2:%d\n",i);
fflush(stdout);
sleep(2);
i++;
}
printf("Thread2 finished!\n");
pthread_exit(NULL);
}
int main()
{
pthread_t thread1,thread2;
if(pthread_create(&thread1,NULL,thread1_proc,NULL)!=0)
perror("Create thread1 failed");
if(pthread_create(&thread2,NULL,thread2_proc,NULL)!=0)
perror("Create thread2 failed");
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
}