Onelong

分享知识,与你一起进步......
RSS icon Home icon
  • linux c 线程同步实例

    post by onelong / 2010-11-26 21:12 Friday [linux]

    看看代码啦!不多说.....

    #include<stddef.h>

    #include<stdio.h>

    #include<unistd.h>

    #include<pthread.h>

     

    void readfun();

    void writefun();

     

    char buf[255];

    int buf_has_item = 0;

    int retflag = 0;

    pthread_mutex_t mutex;

     

    int main()

    {

    pthread_t readPth;

    pthread_mutex_init(&mutex, NULL);/*初始化*/

    pthread_create(&readPth, NULL, (void *)(&readfun), NULL);//创建一个线程

    writefun();

    printf("Parent Thread\n");

    return 0;

    }

     

    void readfun()

    {

    while(1){

    if(retflag)

    return;//结束

    pthread_mutex_lock(&mutex);

    if(buf_has_item == 1)

    {

    printf("%s", buf);

    buf_has_item = 0;

    }

    pthread_mutex_unlock(&mutex);

    }

    }

     

    void writefun()

    {

    int i=0;

    while(1)

    {

    if(i==10)//循环十次结束

    {

    retflag = 1;

    return;

    }

    pthread_mutex_lock(&mutex);

    if(buf_has_item == 0)

    {

    sprintf(buf,"This is %d\n",i++);

    buf_has_item = 1;

    }

    pthread_mutex_unlock(&mutex);

     

    }

    }

    编译运行:

     

    hl@hl-pc:~/桌面/c/thread$ gcc -lpthread test2.c -o test2

    hl@hl-pc:~/桌面/c/thread$ ./test2

    This is 0

    This is 1

    This is 2

    This is 3

    This is 4

    This is 5

    This is 6

    This is 7

    This is 8

    This is 9

    Parent Thread

    标签: linux c 线程 同步
    引用地址:
     

    我要评论