【问题标题】:Output for simple program using pthread使用 pthread 的简单程序的输出
【发布时间】:2013-05-14 14:36:31
【问题描述】:
void cleanupHandler(void *arg) { 
    printf("In the cleanup handler\n");
}
void *Thread(void *string) { 
    int i;
    int o_state;
    int o_type;
    pthread_cleanup_push(cleanupHandler, NULL);
    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &o_state);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &o_type);
    puts("1 Hello World");
    pthread_setcancelstate(o_state, &o_state);
    puts("2 Hello World");
    pthread_cleanup_pop(0);
    pthread_exit(NULL);
}
int main() { 
    pthread_t th;
    int rc;
    rc = pthread_create(&th, NULL, Thread, NULL);
    pthread_cancel(th);
    pthread_exit(NULL);
}

我想知道这段代码的输出是什么以及它们会以什么顺序发生。是的,这是我 6 小时后考试的练习题。任何帮助将不胜感激。今天没有办公时间,因为我大学的所有助教都忙于自己的期末考试。

谢谢

【问题讨论】:

    标签: c++ c multithreading pthreads


    【解决方案1】:

    这里是您需要了解他们将在考试中提出的问题的手册页(这肯定不会是上面的确切问题。)因此您需要了解每个功能的作用。

    在这个问题中(可能是您考试中的类似问题),您需要枚举两个线程之间对这些函数的所有可能交错调用。

    【讨论】:

      【解决方案2】:
      1 Hello World
      2 Hello World
      

      为什么不直接编译并运行它呢?该版本编译运行。

      #include <pthread.h>
      #include <stdio.h>
      #include <stdlib.h>
      #include <unistd.h>
      void cleanupHandler(void *arg) {
          printf("In the cleanup handler\n");
      }
      void* Thread(void *string) {
          int i;
          int o_state;
          int o_type;
          sleep(1);
          pthread_cleanup_push(cleanupHandler, NULL);
      
          sleep(1);//Note that when you uncomment lines, you should uncomment them in order.
          pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &o_state);
          sleep(1);
          pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &o_type);
          puts("1 Hello World");
          sleep(1);
          pthread_setcancelstate(o_state, &o_state);
          sleep(1);
          puts("2 Hello World");
          pthread_cleanup_pop(0);
          pthread_exit(NULL);
      }
      
      int main() {
          pthread_t th;
          int rc;
          rc = pthread_create(&th, NULL, Thread, NULL);
          pthread_cancel(th);
          pthread_exit(NULL);
      }
      

      【讨论】:

      • "为什么不直接编译并运行它?"因为这无助于为考试做准备,你可能会理解为什么会得到这样的结果。
      • 还有 [有/没有?] 其他可能的输出。这就是为什么这是一个很好的练习考试问题。您需要了解哪些函数可以交错,哪些不能。
      • 是的,但有时通过运行并编译它来学习更快,然后尝试强制这些交错情况发生,因为这个例子很简单,实际上这是一个确定性的例子,没有一些涉猎。我个人发现涉足编译后的代码比手册页更有用,这就是为什么我投入了可以为他实际编译和运行的代码。
      • 谢谢你,迈克。如果我有能力在我所处的当前环境中运行,我就会有。另外,我对这些东西还很陌生,所以我也想知道为什么它会给我某些输出。
      • 也感谢您提供指向手册页的链接。这非常有帮助。谢谢你们!!!
      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      相关资源
      最近更新 更多