【问题标题】:critical section definition临界区定义
【发布时间】:2013-04-07 23:04:59
【问题描述】:

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

【问题讨论】:

  • void *thread_result 缺失;
  • 很难对损坏的代码进行推理。修复潜在的无限循环while (number != 0) sleep(1);

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-17
    • 2013-03-26
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多