两个线程将使用相同的func().两个线程应该是互斥的.如何让它正常工作?
(输出应为"abcdeabcde")
char arr[] = "ABCDE";
int len = 5;
void func() {
for(int i = 0; i <len;i++)
printf("%c",arr[i]);
}
Run Code Online (Sandbox Code Playgroud)
创建互斥锁?假设你正在使用pthread,
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
....
void func() {
int errcode = pthread_mutex_lock(&mutex);
// deal with errcode...
// printf...
errcode = pthread_mutex_unlock(&mutex);
// deal with errcode...
}
Run Code Online (Sandbox Code Playgroud)
有关教程,请参阅https://computing.llnl.gov/tutorials/pthreads/#Mutexes.