依睛(IT blog) 我回来了,PHP<-->C/C++ LINUX

笨鸟

统计

积分与排名

友情连接

最新评论

线程同步

这东西会很容易让新手看懂, 希望能对大家有助,

线程同步, 只有实践才能学到东西, 理论看懂就行了, 动动手.
要少用全局变量.  我的代码都可以运行, 如有问题可联系我.

我blog 上有联系方式.

#include <semaphore.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

sem_t       sem_1;
sem_t       sem_2;

void *thread2(void *arg)
{
    printf("sss\n");
    int i=-1;
   
    while(1)
    {
        sem_wait(&sem_2);
        printf("11111value: %d\n", i+=2);
        sleep(1);
        sem_post(&sem_1);
    }
}

void *thread1(void *arg2)
{
    printf("222\n");
    int i=0;

    while(1)
    {
        sem_post(&sem_2);
        sem_wait(&sem_1);
        printf("22222value: %d\n", i+=2);
        sleep(1);
    }
}


int main()
{
    pthread_t   t1;
    pthread_t   t2;

   
    sem_init(&sem_1, 0, 0);
    sem_init(&sem_2, 0, 0);

    pthread_create(&t1, NULL, thread1, NULL);
    sleep(2);
    pthread_create(&t2, NULL, thread2, NULL);
   
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
   
    return 0;
}

 

posted on 2008-11-17 13:41 向左向右走 阅读(269) 评论(0)  编辑 收藏 引用 所属分类: C/C++学习资料库Linux 学习库

只有注册用户登录后才能发表评论。