取消 pthread 和 printf 行为

rom*_*m1v 5 c printf pthreads cancellation

下面是 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;
}
Run Code Online (Sandbox Code Playgroud)

我编译:

gcc -pthread -Wall threadtest.c -o threadtest
Run Code Online (Sandbox Code Playgroud)

执行时,有时会在 后 sleep(1)打印一个附加数字。

有时这个数字是重复的:

0
1
2
3
4
4  // printed after sleep(1)
Run Code Online (Sandbox Code Playgroud)

有时不是:

0
1
2
3
4
5  // printed after sleep(1)
Run Code Online (Sandbox Code Playgroud)

如果 I fflush(stdout)before sleep(1),则立即打印附加号码。

printf取消线程时如何避免这种奇怪的行为?

谢谢。

alk*_*alk 1

您可以在执行以下操作时禁用取消printf()并添加显式取消点:

int cancel_state = 0;
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel_state);
printf("%d\n", i);
pthread_setcancelstate(cancel_state);
pthread_testcancel();
Run Code Online (Sandbox Code Playgroud)

(为了可读性而省略了错误检查)