Chinaunix首页 | 论坛 | 博客
  • 博客访问: 279592
  • 博文数量: 109
  • 博客积分: 2116
  • 博客等级: 大尉
  • 技术积分: 1062
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-22 15:38
文章分类

全部博文(109)

文章存档

2013年(2)

2011年(16)

2010年(90)

2009年(1)

我的朋友

分类: 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。否则不能进行。

阅读(324) | 评论(0) | 转发(0) |
0

上一篇:多进程实验

下一篇:线程属性设置

给主人留下些什么吧!~~