c++ - pthread 返回 251

标签 c++ multithreading pthreads

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);
   }

最佳答案

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

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


您是否链接了 -lpthread?

您应该使用 errno.h 查看您的系统上的错误 251 或这应该给您更详细的消息:

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

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

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

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

[EAGAIN] 系统缺少创建所需的资源 另一个线程,或系统强加的限制 进程中的线程总数 将超过 [PTHREAD_THREADS_MAX]。

[EINVAL] attr 指定的值无效。

关于c++ - pthread 返回 251,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/737102/

相关文章:

c++ - 如何通过类构造函数访问私有(private)静态成员变量?

来回发送的条件变量

c - 什么时候销毁 pthread 屏障是安全的?

java - 创建 Java native 接口(interface)的问题

c++ - 模板类实例化中的指针转换无效

我可以在我开发的多线程应用程序中利用多核吗

java - 多线程单例

c - pthread_detach 不会改变任何东西

c - pthread条件变量和mutex,程序出现死锁

c++ - 大括号中发生了什么