使用睡眠在 C 中线程化

Diw*_*rma 0 c linux multithreading pthreads

我正在学习 C 线程概念,并编写了下面的简单代码。现在,当我编译并运行它时,会出现随机行为,例如意外打印。

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

void * func_threadName(void * i) {

    int *x=(int *)i;
    printf("I'm thread : %d\n",*x);

return NULL;
}
main()
{
    int iter;
    printf("testing multithreading....\n");

    pthread_t thread_arr[3];

    for (iter=0;iter<3;iter++)
    {
        pthread_create(&thread_arr[iter],NULL,func_threadName,&iter);

    }

     for (iter=0;iter<3;iter++)
     {
         pthread_join(thread_arr[iter],NULL);
     }
}
Run Code Online (Sandbox Code Playgroud)

它打印出不可预测的像:

diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o 
testing multithreading....
I'm thread : 0
I'm thread : 0
I'm thread : 0
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o 
testing multithreading....
I'm thread : 0
I'm thread : 2
I'm thread : 1
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o 
testing multithreading....
I'm thread : 2
I'm thread : 2
I'm thread : 0
Run Code Online (Sandbox Code Playgroud)

但是当我在创建线程后进行如下轻微更改时,它可以完美运行并按顺序打印。

pthread_create(&thread_arr[iter],NULL,func_threadName,&iter);
        sleep(1);
Run Code Online (Sandbox Code Playgroud)

现在每次输出都是这样:

diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o 
testing multithreading....
I'm thread : 0
I'm thread : 1
I'm thread : 2
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o 
testing multithreading....
I'm thread : 0
I'm thread : 1
I'm thread : 2
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o 
testing multithreading....
I'm thread : 0
I'm thread : 1
I'm thread : 2
Run Code Online (Sandbox Code Playgroud)

我想了解在第一种情况下,是否显示了不可预测的行为,因为所有线程共享相同的内存空间,因此在一个线程终止之前,另一个线程使用相同的 i 值?欢迎提供任何其他信息。

Som*_*ude 5

您无法准确判断线程何时运行,因此主线程可能会继续运行,从而更改其循环中的计数器。由于该循环计数器是一个指针,所有线程都具有指向完全相同变量的相同指针。您还可以在第二个循环中使用相同的变量,因此可以在线程的生命周期内对其进行两次修改。

“按原样”传递数字会更好(尽管更“hackish”):

pthread_create(&thread_arr[iter], NULL, func_threadName, (void *) iter);
Run Code Online (Sandbox Code Playgroud)

然后在线程函数中像这样获取它:

int x = (int) i;
Run Code Online (Sandbox Code Playgroud)

  • -1 不,不是更好,而是更糟。当人们可以简单地声明一个数组来保存值时,为什么要进行黑客攻击?坏的。 (2认同)