文章详情

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

多线程编程实例

时间:2010-08-27  来源:huazaicola

通过创建两个线程来实现对一个数的递加。    可见:用pthread_join,多个线程同步执行,主进程等待所有线程终止后执行。

/*function: a multiple thread programming in linux
 *author: Andy
 *E-mail : [email protected]
 */
#include <pthread.h>
#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#define MAX 10

pthread_mutex_t mut;
pthread_t pthread[2];
int a = 0, i;

void *pthread0(void)
{
    for(i = 0; i < MAX; i++)
    {
    printf("thread0 : a = %d\n", a);
    pthread_mutex_lock(&mut);
        a++;
    pthread_mutex_unlock(&mut);
    sleep(3);
    }
    pthread_exit(NULL);
}

void *pthread1(void)
{    for(i = 0; i < MAX; i++)
    {
    printf("thread1 : a = %d\n", a);
    pthread_mutex_lock(&mut);
        a++;
    pthread_mutex_unlock(&mut);
    sleep(2);
    }
    pthread_exit(NULL);
}
void mypthread_create(void)
{
    memset(pthread, 0, sizeof(pthread));

    if(pthread_create(&pthread[0], NULL, (void *)pthread0, NULL) != 0)
    {
        printf("creat 0 error\n");
        exit(1);
    }
    else
    {
        printf("pthread0 ok\n");
    }
    if(pthread_create(&pthread[1], NULL, (void *)pthread1, NULL) != 0)
    {
        printf("creat 1 error\n");
        exit(1);
    }
    else
    {
        printf("pthread1 ok\n");
    }
}

void pthread_wait(void)
{
    if(pthread[0] != 0)
    {
        pthread_join(pthread[0], NULL);
    }
    if(pthread[1] != 0)
    {
        pthread_join(pthread[1], NULL);
    }
}

int main(void)
{
    pthread_mutex_init(&mut, NULL);
    
    mypthread_create();
    
    pthread_wait();
    
    return 0;
}

执行结果:

[gh@localhost pthread]$ ./add
pthread0 ok
pthread1 ok
thread0 : a = 0
thread1 : a = 0
thread1 : a = 2
thread0 : a = 3
thread1 : a = 4
thread0 : a = 5
thread1 : a = 6
thread1 : a = 7
thread0 : a = 8
thread1 : a = 9
thread0 : a = 10


注意:

1.学习代码风格, 多函数,结构清晰,可读性强  全局变量的使用

易错点: if(pthread_create(&pthread[0], NULL, (void *)pthread0, NULL) != 0)
  此处pthread0,线程函数作为参数时的应用!不太明白

部分参考:http://tieba.baidu.com/f?kz=363207210

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载