我编写了这个程序,假设在主循环的每次迭代中创建一个新线程并让它打印迭代变量。例如。在第一次迭代中,创建一个新线程,它应该打印" arg:0",下一次迭代打印" arg:1"等等。
正如您在下面的屏幕截图中看到的那样,arg 3& 7打印两次,而它只打印一次。现在,如果我在每次迭代中添加sleep(1),它就会起作用,因此它会出现某种并发问题。请注意,每次结果都是完全随机的,每次不仅仅是3和7。
有人有想法吗?谢谢!
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
static void * mutex_thread(void * arg);
int threads_amt = 10;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main (void)
{
pthread_t threads[threads_amt];
// Create threads.
for(int i = 0; i < threads_amt; i++)
{
printf ("Starting thread [%d]...\n", i);
// Create thread.
pthread_create (&threads[i], NULL, mutex_thread, &i);
// IT WORKS IF I ENABLE sleep(1).
//sleep (1);
printf ("Thread created.\n\n");
}
// Join threads.
printf("Joining threads...\n");
for(int i = 0; i < threads_amt; i++)
{
pthread_join (threads[i], NULL);
}
return (0);
}
static void * mutex_thread(void * arg)
{
// Lock mutex.
pthread_mutex_lock (&mutex);
// Print arg.
int *number = (int*)arg;
printf("arg: %d\n", *number);
// Unlock mutex.
pthread_mutex_unlock (&mutex);
return (NULL);
}