线程是程序执行的最小单位,每个进程都是一个独立的运行单位,拥有各自的权利和责任
线程的优点:
1、开销小
2、线程间方便通信,由于同一进程下的线程之间共享数据空间,所以一个线程的数据可直接为其他线程所用
线程API
1、线程的创建
pthread_create
函数的作用:创建一个进程
函数的原型:pthread_create(pthread_t *thread,pthread_addr_t *addr,void *(*start_routine)(void *),void *arg)
函数的参数:thread:线程的标识符
attr:线程的属性,一般设为NULL
start_routine:线程的执行函数
arg:传入到线程执行函数的参数
返回值:成功:0;出错:-1
头文件:#include<pthread.h>
函数的实现函数:
#include <stdio.h>
#include <pthread.h>
void *myThread1(void)
{
int i;
for (i=0; i<100; i++)
{
printf("This is the 1st pthread,created by zieckey.\n");
sleep(1);//Let this thread to sleep 1 second,and then continue to run
}
}
void *myThread2(void)
{
int i;
for (i=0; i<100; i++)
{
printf("This is the 2st pthread,created by zieckey.\n");
sleep(1);
}
}
int main()
{
int i=0, ret=0;
pthread_t id1,id2;
/*创建线程1*/
ret = pthread_create(&id1, NULL, (void*)myThread1, NULL);
if (ret)
{
printf("Create pthread error!\n");
return 1;
}
/*创建线程2*/
ret = pthread_create(&id2, NULL, (void*)myThread2, NULL);
if (ret)
{
printf("Create pthread error!\n");
return 1;
}
pthread_join(id1, NULL);
pthread_join(id2, NULL);
return 0;
}
2、线程的退出
pthread_exit
函数的作用:线程的退出
函数的原型:void pthread_exit(void *retval)
3、pthread_join
函数的作用:等待进程的退出
函数的原型:int pthread_join(pthread_t th,void **thread_return)
函数的参数:th:线程的标识符
thread_return:不为NULL时,存储线程结束时的返回值
返回值:成功:0;出错:-1
函数实现代码:
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
void *thread(void *str)
{
int i;
for (i = 0; i < 10; ++i)
{
sleep(2);
printf( "This in the thread : %d\n" , i );
}
return NULL;
}
int main()
{
pthread_t pth;
int i;
int ret = pthread_create(&pth, NULL, thread, (void *)(i));
pthread_join(pth, NULL);
printf("123\n");
for (i = 0; i < 10; ++i)
{
sleep(1);
printf( "This in the main : %d\n" , i );
}
return 0;
}
线程之间资源的竞争:
1、互斥量
2、信号灯
3、条件变量