这是一个 pthread 取消的代码示例:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void *my_routine(void *arg) {
int i;
for (i = 0; i < 10; i++) {
printf("%d\n", i);
}
return NULL;
}
int main(void) {
pthread_t thread;
if (pthread_create(&thread, NULL, my_routine, NULL)) {
fprintf(stderr, "Cannot create pthread\n");
return 1;
}
usleep(20);
pthread_cancel(thread);
pthread_join(thread, NULL);
//fflush(stdout);
sleep(1);
return 0;
}
我编译:
gcc -pthread -Wall threadtest.c -o threadtest
执行时,有时会在 sleep(1)
.
有时这个数字是重复的:
0
1
2
3
4
4 // printed after sleep(1)
有时不是:
0
1
2
3
4
5 // printed after sleep(1)
如果 I fflush(stdout)
before sleep(1)
,则立即打印附加号码。
printf
取消线程时如何避免这种奇怪的行为?
谢谢你。