【发布时间】:2022-01-08 07:01:08
【问题描述】:
首先,我对 posix 编程还很陌生,并且仍然了解基本概念。我仍然不太清楚pthread_mutex_lock
pthread_mutex_unlock 工作。
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <pthread.h>
#inlcude <stdio.h>
pthread_mutex_t_mtx;
void* routine(void* i){
int j;
for(j = 0; j < 1000000; ++j){
pthread_mutex_lock(&mtx);
printf("Inside thread %d\n", i);
pthread_mutex_unlock(&mtx);
}
return NULL;
}
int main()
{
pthread_t th[3];
int i;
pthread_mutex_init(&mtx, NULL);
for(i = 1; i <= 2; ++i)
{
if(pthread_create(th + i, NULL, routine, i){
perror(NULL); return 1;
}
}
for(i = 1; i <=2; ++i)
pthread_join(th[i], NULL);
return 0;
}
上述程序的正确输出应该是什么?我认为由于互斥锁的锁定和解锁,会有 2000000 次迭代,但我不太清楚它们完成的顺序。第一个线程是否执行 for 的前 1000000 步?它甚至执行 20000000 中的第一个吗?还是因为秩序更加混乱?
【问题讨论】:
-
鉴于
void *i,printf("Inside thread %d\n", i);是错误的。void *的正确格式说明符是%p。