1

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

2 回答 2

4

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

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


您是否与-lpthread 链接?

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

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

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

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

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

[EAGAIN] 系统缺乏创建另一个线程所需的资源,否则将超出系统对进程 [PTHREAD_THREADS_MAX] 中线程总数的限制。

[EINVAL] attr 指定的值无效。

于 2009-04-10T09:04:29.277 回答
0

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

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

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

于 2009-04-10T09:11:27.637 回答