我正在编写的 C 线程代码出现问题

问题描述 投票:0回答:1

我正在编写一个简单的多线程代码,该代码在线程的被调用函数中递增变量。使用 for 循环创建线程,并且还想在每个线程中打印循环变量 i。

这是片段

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

#define N 10

static int a = 0;
pthread_mutex_t mut;
pthread_mutex_t muti;

void *
dummy(void *data)
{
    pthread_mutex_lock(&mut);
    a++;
    pthread_mutex_unlock(&mut);
    printf("In the dummy function.. thread %d \n", *(int *) data);
}

int
main()
{
    int ret;
    pthread_t array[N];

    pthread_mutex_init(&mut, NULL);
    pthread_mutex_init(&muti, NULL);

    for (int i = 0; i < 10;) {
        pthread_mutex_lock(&muti);
        i++;
        pthread_mutex_unlock(&muti);

        ret = pthread_create(&array[i], NULL, &dummy, &i);

        if (ret != 0) {
            printf("Error with code %d.. \n", ret);
            return i;
        }

        printf(" a value is: %d\n", a);
    }

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

    pthread_mutex_destroy(&mut);
    pthread_mutex_destroy(&muti);

    return 0;
}

这是相同的输出:

a value is: 0
In the dummy function.. thread 1
a value is: 1
In the dummy function.. thread 3
a value is: 2
In the dummy function.. thread 4
a value is: 3
In the dummy function.. thread 5
a value is: 4
In the dummy function.. thread 5
a value is: 5
In the dummy function.. thread 7
a value is: 6
In the dummy function.. thread 8
a value is: 7
In the dummy function.. thread 8
a value is: 8
In the dummy function.. thread 9
a value is: 9
In the dummy function.. thread 10

程序挂在最后 期望在虚拟函数中之前先打印一个值 程序正确终止

c multithreading process operating-system
1个回答
0
投票
在您的第一个

for

 循环中,您的 
i++
 放置得不好。

当你拥有它时,在使用

i

store 存储到 
&array[i]
之前,先增加
pthread_create

因此,您将在第一次循环迭代时存储到

pthread[1]

 中。

pthread[0]

never 设置为任何内容。

因此,当您在

pthread[0]

 的循环中访问 
pthread_join
 时,您会遇到 UB(未定义行为)和[可能]段错误。

i++

 移至第一个 
for
 语句的增量部分。

改变:

for (int i = 0; i < 10;) { pthread_mutex_lock(&muti); i++; pthread_mutex_unlock(&muti); ret = pthread_create(&array[i], NULL, &dummy, &i); ... }
进入:

for (int i = 0; i < 10; i++) { pthread_mutex_lock(&muti); pthread_mutex_unlock(&muti); ret = pthread_create(&array[i], NULL, &dummy, &i); ... }
    
© www.soinside.com 2019 - 2024. All rights reserved.