分类: LINUX
2010-07-09 14:41:54
今天完成基本的线程编程操作。
用到的系统调用有:pthread_creat, pthread_join, pthread_exit, pthread_cancel等
可以对照进程中的:fork, waitpid, exit等加深印象。
本实例创建3个线程,并发执行。源代码来自华清远见。
#include
#include
#include
#define THREAD_NUMBER 3//线程数
#define REPEAT_NUMBER 5//每个线程中的最小任务数
#define DELAY_TIME_LEVELS 10.0//小任务之间的最大时间间隔
void *thrd_func(void *arg)//线程函数
{
int thrd_num = (int)arg;
int delay_time = 0;
int count = 0;
printf("Thread %d is starting\n", thrd_num);
for(count = 0; count < REPEAT_NUMBER; count++)
{
delay_time = (int) (rand() *DELAY_TIME_LEVELS/(RAND_MAX) + 1);
sleep(delay_time);
printf("\tThread %d: job %d delay = %d\n", thrd_num, count, delay_time);
}
printf("Thread %d finished\n", thrd_num);
pthread_exit(NULL);//终止线程
}
int main()
{
pthread_t thread[THREAD_NUMBER];
int no = 0, res;
void *thrd_ret;
srand(time(NULL));//随机
for(no = 0; no < THREAD_NUMBER; no++)
{
res = pthread_create(&thread[no], NULL, thrd_func, (void*)no);//创建多线程
if(res != 0)
{
printf("Create thread %d failed\n", no);
exit(res);
}
}
printf("Create threads success\nWaiting for threads to finish..\n");
for(no = 0; no < THREAD_NUMBER; no++)
{
res = pthread_join(thread[no], &thrd_ret);//等待线程结束
if(!res)
{
printf("Thread %d joined\n", no);
}
else
{
printf("Thread %d join failed\n", no);
}
}
return 0;
}
编译连接执行结果如下:
注:编译时候要加后缀 -lpthread。否则不能进行。