线程是进程基本的基本调度单位。而进程是程序执行和资源分配的最小单位。可以减少资源的开销.
线程有专门的线程库来调用Thread.线程的创建用thread_create();
int pthread_create(pthread_t *restrict thread,const pthread_attr_t *restrict attr,
void *(*start_routine)(void*), void *restrict arg);
参数1 :线程的标志
参数2 :线程的属性
参数3 :线程函数
参数4 :线程传递的参数
线程的退出 pthread_exit(void *value_ptr)
等待线程结束
int pthread_join(pthread_t thread, void **value_ptr)
示例程序
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int global_variable;
void * test1()
{
while(1)
{
sleep(2);
global_variable++;
printf(" global_variable is %d \r\n",global_variable);
if(global_variable>5)
pthread_exit(0);
}
}
void *test2()
{
while(1)
{
sleep(3);
global_variable--;
printf(" global_variable is %d \r\n",global_variable);
if(global_variable<0)
pthread_exit(0);
}
}
int main(int argc,char *argv[])
{
pthread_t id1,id2;
int bit;
bit=pthread_create(&id1,NULL,test1,NULL);
if(bit!=0)
{
printf("id1 create error\r\n");
exit(0);
}
bit=pthread_create(&id2,NULL,test2,NULL);
if(bit!=0)
{
printf("id2 create error\r\n");
exit(0);
}
pthread_join(id1,NULL);
pthread_join(id2,NULL);
return 0;
}
结果如下
id1global_variable is 1
id2global_variable is 0
id1global_variable is 1
id2global_variable is 0
id1global_variable is 1
id1global_variable is 2
id2global_variable is 1
id1global_variable is 2
id2global_variable is 1
id1global_variable is 2
id1global_variable is 3
id2global_variable is 2
id1global_variable is 3
id2global_variable is 2
id1global_variable is 3
id1global_variable is 4
id2global_variable is 3
id1global_variable is 4
id2global_variable is 3
id1global_variable is 4
id1global_variable is 5
id2global_variable is 4
id1global_variable is 5
id2global_variable is 4
id1global_variable is 5
id1global_variable is 6
id2global_variable is 5
id2global_variable is 4
id2global_variable is 3
id2global_variable is 2
id2global_variable is 1
id2global_variable is 0