c - pthread_mutex_t 位于结构体内部并在访问时锁定该结构体

标签 c linux multithreading locking mutex

我有一个全局结构指针,我已经完成了一个 malloc (10 个结构的数组),并且我已将该结构的一个实例发送给每个线程,并且在将此结构实例作为参数传递给 pthread_create() 之前,正在更新该结构成员(member)值(value)。在每个线程内,我将锁定并打印成员值。

我创建了另一个线程,在其中传递整个结构实例,我锁定每个结构实例并打印它,但每次它打印 0。您能否建议我必须进行哪些更改。

我不想使用任何线程条件,因为我在每个线程中休眠以进行线程切换。

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

struct lock_check{
    int value;
    pthread_mutex_t lock; 
}; 
struct lock_check *check;

void* trythis(void *arg) 
{
    struct lock_check *thread = (struct lock_check *)arg;
    while(1){
        pthread_mutex_lock(&thread->lock); 
        printf("Inside Thread with value:%d\n", thread->value); 
        pthread_mutex_unlock(&thread->lock); 
        sleep(1);
    }
    return NULL; 
}

void* printthis(void *arg) 
{
    printf("Entering printthis thread\n");
    struct lock_check *print_thread = (struct lock_check *)arg;
    for(int i = 0; i < 10; i++){
        pthread_mutex_lock(&print_thread[i].lock); 
        printf("Printing value :%d\n", print_thread[i].value); 
        pthread_mutex_unlock(&print_thread[i].lock); 
    }
    return NULL; 
}
int main(void) 
{ 
    int i = 0; 
    int error; 
    check = malloc(sizeof(struct lock_check) * 10);
    pthread_t tid[10];
    pthread_t tid_read;

    for (int i = 0; i < 10; i++) {
        check[i].value = i;
        error = pthread_create(&(tid[i]), NULL, &trythis, &check[i]); 
        if (error != 0) 
            printf("\nThread can't be created :[%s]", strerror(error)); 
    }
    sleep(5);
    printf("creating printthis thread\n");
    error = pthread_create(&tid_read, NULL, &printthis, &check);
    for (int i = 0; i < 10; i++) {
        pthread_join(tid[i], NULL); 
    }
    pthread_join(tid_read, NULL); 
    return 0; 
} 

最佳答案

error = pthread_create(&tid_read, NULL, &printthis, &check);

pthread_create 需要 void *,但您传递的 struct lock_check ** 具有未定义的行为。

将其更改为。

error = pthread_create(&tid_read, NULL, &printthis, check);

关于c - pthread_mutex_t 位于结构体内部并在访问时锁定该结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58010123/

相关文章:

c - 通过权重调整范围

linux - Bash:将程序输出的每一行重定向到实时文件

java - 为什么将 GC 限制为 1 个线程会提高性能?

python - 如何在 wxPython TextCtrl 中捕获在单独进程中运行的 shell 脚本的输出?

c++ - 为什么(无限)递归在 clang(和 gcc/g++)中使用 和 w/o -O3 会给出不同的结果?

c - 我希望能够测量这两个函数的执行时间,但无法理解它

c - 传递栈顶指针作为参数

linux - 从目录中打开 Sublime Text 中的所有文件,明确指定的文件除外

linux - 交叉编译nginx-1.0.11

iphone - PerformSelectorInBackgroundThread 和 NSTimer