关键部分定义

时间:2013-04-15 18:05:53

标签: c linux operating-system pthreads critical-section

在下面的示例代码中,“临界区”在哪里?在“sem_wait()”之后?

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

void * thread_snd(void *arg);
void * thread_rcv(void *arg);
sem_t bin_sem;
int number=0;

char thread1[]="A Thread";
char thread2[]="B Thread";
char thread3[]="C Thread";

int main(int argc, char **argv)
{
    pthread_t t1, t2, t3;
    void *thread_result;
    int state;
    state = sem_init(&bin_sem, 0, 0);

    pthread_create(&t1, NULL, thread_snd, &thread1);
    pthread_create(&t2, NULL, thread_rcv, &thread2);
    pthread_create(&t3, NULL, thread_rcv, &thread3);
    pthread_join(t1, &thread_result);
    pthread_join(t2, &thread_result);
    pthread_join(t3, &thread_result);
    printf("number : %d \n", number);
    sem_destroy(&bin_sem);

    return 0;
}

void * thread_snd(void * arg)
{
    int i;
    for(i=0; i<4; i++)
    {
        while(number != 0)
            sleep(1);
        number++;
        printf("%s, number : %d \n", (char*)arg, number);
        sem_post(&bin_sem);
    }
}

void * thread_rcv(void * arg)
{
    int i;
    for(i=0; i<2; i++)
    {
        sem_wait(&bin_sem);
        number--;
        printf("%s, number : %d \n", (char*)arg, number);
    }
}

1 个答案:

答案 0 :(得分:1)

在提供的代码中实际上没有“关键部分”,只有“同步点”,并且是用信号量实现的。关键部分也可以用信号量实现,但是线程必须同时使用sem_wait()sem_post(),但在大多数情况下,互斥体用于关键部分(如果只有一个线程应该输入它)