1

可以请任何人让我知道我的代码出了什么问题。我一次只希望一个线程访问关键区域,但所有线程都进入。

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

pthread_t th[5];
pthread_mutex_t mutex_for_some_value;
int value;

void * thread_talk(void * arguments) {

    while (1) {

        pthread_mutex_lock(&mutex_for_some_value);

        printf("\n Now Accessed by %d", *((int*) arguments));

        pthread_mutex_unlock(&mutex_for_some_value);
        sleep(2);

        printf("\n\n Thread %d is left critical section", *((int*) arguments));
    }

    return NULL;
}

int main(int argc, char **argv) {

    int count[5] = { 1, 2, 3, 4, 5 };

    printf("\n %d", pthread_mutex_init(&mutex_for_some_value, NULL));

    for (int i = 0; i < 5; i++) {
        printf("\n Creating %d thread", count[i]);
        pthread_create(&th[i], NULL, &thread_talk, (void*) &count[i]);
    }

    for (int i = 0; i < 5; ++i) {
        pthread_join(th[i], NULL);
    }

    pthread_mutex_destroy(&mutex_for_some_value);

    printf("\n Main done");

    return 0;
}

现在由于互斥锁存在,所以没有两个线程应该进入我的关键区域。但输出是

0 创建 1 个线程

创建 2 个线程

创建 3 个线程

创建 4 个线程

创建 5 个线程

现在由 4 人访问

现在由 3 人访问

现在有 2 人访问

现在有 1 人访问

现在由 5 人访问

线程 4 是左临界区 现在由 4 访问

线程 3 是左临界区 现在由 3 访问

线程 1 是左临界区 现在被 1 访问

线程 2 是左临界区 现在被 2 访问

线程 5 是左临界区

4

1 回答 1

2

该行:

sleep(2)

将延迟“线程 X 处于临界区”输出,直到另一个线程打印“现在由 Y 访问”之后。锁定应该仍然有效。

于 2013-10-11T07:35:50.537 回答