在下面的示例代码中,“关键部分”具体在哪里?。在“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);
    }
}

最佳答案

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

09-28 11:35