文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>linux 多线程程序编译问题

linux 多线程程序编译问题

时间:2010-04-13  来源:lj85214

Linux多线程编程
要用到pthread类库,用pthread_create()函数创建线程,包涵在pthread.h头文件中.下面是示例代码:
编译的时候应该添加pthread类库的连接,否则会产生错误,编译命令为:
#gcc create_thread.c -o create_thread -lpthread -Wall

/*create_thread.c*/
#i nclude <stdio.h>       /* standard I/O routines                 */
#i nclude <pthread.h>     /* pthread functions and data structures */

/* function to be executed by the new thread */
void*
do_loop(void* data)
{
    int i;            /* counter, to print numbers */
    int j;            /* counter, for delay        */
    int me = *((int*)data);     /* thread identifying number */

    for (i=0; i<10; i++) {
    for (j=0; j<500000; j++) /* delay loop */
        ;
        printf("'%d' - Got '%d'\n", me, i);
    }

    /* terminate the thread */
    pthread_exit(NULL);
}

/* like any C program, program's execution begins in main */
int
main(int argc, char* argv[])
{
    int        thr_id;         /* thread ID for the newly created thread */
    pthread_t  p_thread;       /* thread's structure                     */
    int        a         = 1;  /* thread 1 identifying number            */
    int        b         = 2;  /* thread 2 identifying number            */

    /* create a new thread that will execute 'do_loop()' */
    thr_id = pthread_create(&p_thread, NULL, do_loop, (void*)&a);
    /* run 'do_loop()' in the main thread as well */
    do_loop((void*)&b);
   
    /* NOT REACHED */
    return 0;
}


注:pthread_create()在pthread.h中的描述为:
extern int pthread_create (pthread_t *__restrict __threadp,
               __const pthread_attr_t *__restrict __attr,
               void *(*__start_routine) (void *),
               void *__restrict __arg) __THROW;
函数有四个参数,第一个为pthread_t结构指针,用来存放线程的相关信息,第二个参数用来设置线程的相关属性,第三个参数用来指定CallBack函数,第四个参数用来传递参数.
线程的CallBack函数应该是一个返回值为void的指针,并且参数也为void指针.我个人感觉这就像C#中的object的装箱与拆箱,把对象封装后传递.
排行榜 更多 +
百炼英雄抽卡技巧指南

百炼英雄抽卡技巧指南

休闲益智 下载
英雄没有闪滚雷旋风技能如何搭配

英雄没有闪滚雷旋风技能如何搭配

休闲益智 下载
英雄没有闪雷旋风BD构筑推荐

英雄没有闪雷旋风BD构筑推荐

休闲益智 下载