- 子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码
[X] 无法锁住的错误解法
#include "comm.h"
pthread_mutex_t gmux = PTHREAD_MUTEX_INITIALIZER;
#define lock pthread_mutex_lock
#define unlock pthread_mutex_unlock
int cnt = 0;
int sta = 1;
volatile int status = 1;
void *child(void *arg) {
int i = 0;
while(1) {
if (!status) {
printf("child over\n");
break;
}
lock(&gmux);
for (i = 0; i < 10; i++) {
printf("child %d\n", i + 1);
}
unlock(&gmux);
sched_yield();
}
return NULL;
}
int main(int argc, char **argv) {
int i;
pthread_t tid;
pthread_create(&tid, NULL, child, NULL);
while(1) {
sched_yield();
lock(&gmux);
for (i = 0; i < 100; i++) {
printf("parent %d\n", i + 1);
}
if (100 == cnt) {
status = 0;
unlock(&gmux);
break;
}
unlock(&gmux);
cnt++;
}
printf("parent over\n");
return 0;
}
解法一:
#include "comm.h"
pthread_mutex_t gmux = PTHREAD_MUTEX_INITIALIZER;
#define lock pthread_mutex_lock
#define unlock pthread_mutex_unlock
int cnt = 0;
int sta = 1;
volatile int status = 1;
void *child(void *arg) {
int i = 0;
while(1) {
do {
unlock(&gmux);
sched_yield();
lock(&gmux);
} while (0 == sta);
if (!status) {
printf("child over\n");
break;
}
for (i = 0; i < 10; i++) {
printf("child %d\n", i + 1);
}
sta = 0;
}
return NULL;
}
int main(int argc, char **argv) {
int i;
pthread_t tid;
pthread_create(&tid, NULL, child, NULL);
while(1) {
do {
unlock(&gmux);
sched_yield();
lock(&gmux);
} while(1 == sta);
for (i = 0; i < 100; i++) {
printf("parent %d\n", i + 1);
}
if (100 == cnt) {
status = 0;
unlock(&gmux);
break;
}
sta = 1;
cnt++;
}
printf("parent over\n");
return 0;
}
解法二:(用条件变量)