【问题标题】:pthread returns 251pthread 返回 251
【发布时间】:2009-04-10 08:59:14
【问题描述】:

pthread_create 返回值 251 而不创建线程。有谁知道问题是什么?请帮忙。机器是 HP-UX。

我是多线程的新手。

   #include <stdio.h>
   #include <stdlib.h>
   #include <pthread.h>

   void *print_message_function( void *ptr );

   main()
   {
        pthread_t thread1, thread2;
        char *message1 = "Thread 1";
        char *message2 = "Thread 2";
        int  iret1, iret2;
        /* Create independent threads each of which will
         * execute function */

        iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
        iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);

        /* Wait till threads are complete before
         * main continues. Unless we  */
        /* wait we run the risk of executing an
         * exit which will terminate   */
        /* the process and all threads before the
         * threads have completed.   */

        pthread_join( thread1, NULL);
        pthread_join( thread2, NULL);
        printf("Thread 1 returns: %d\n",iret1);
        printf("Thread 2 returns: %d\n",iret2);
        exit(0);
   }

   void *print_message_function( void *ptr )
   {
        char *message;
        message = (char *) ptr;
        printf("%s \n", message);
   }

【问题讨论】:

    标签: c++ multithreading pthreads


    【解决方案1】:

    编辑:在 HP-UX11 上。 pthread_create 失败并出现错误 251:函数不可用。

    检查 -lc 在您的链接顺序中是否位于 -lpthread 之前。 如果是这种情况,那么调用将解析为 C 库中的存根 并可能导致此错误。


    您是否与 -lpthread 链接?

    您应该使用 errno.h 来查看您的系统上有什么错误 251,或者这应该会给您一个更详细的消息:

    printf("%s\n", strerror(errno));
    

    此外,在使用 pthread 时,您应该检查几乎每次调用 pthread* 的返回值(请参阅每个函数的 man 以检查可能返回的错误)

    对于 pthread_create,您至少有 2 个可能的错误(取决于您的系统和 pthread 实现):

    如果出现以下情况,pthread_create() 将失败:

    [EAGAIN] 系统缺乏必要的资源来创建 另一个线程,或系统对 进程中的线程总数 将超过 [PTHREAD_THREADS_MAX]。

    [EINVAL] attr 指定的值无效。

    【讨论】:

      【解决方案2】:

      这在我的 Linux 机器上编译并运行,结果如下:

      Thread 1
      Thread 2
      Thread 1 returns: 0
      Thread 2 returns: 0
      

      所以看起来问题不在于您的代码,而在于环境。我已经 10 多年没有使用 HP-UX 了,所以我帮不了你。

      【讨论】:

      • 是的,看起来和环境有关。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 2019-03-03
      • 2021-11-21
      • 1970-01-01
      相关资源
      最近更新 更多