+ -
当前位置:首页 → 问答吧 → 多线程-linux

多线程-linux

时间:2010-08-23

来源:互联网

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>

  4. void thread( void )
  5. {
  6.         int i ;
  7.         for ( i = 0; i < 3; ++i )
  8.         {
  9.                 printf("this is a pthread\n");
  10.         }
  11. }


  12. int main()
  13. {
  14.         pthread_t id;
  15.         int i , ret;

  16.         ret = pthread_create( &id, NULL, (void *)thread, NULL );
  17.         if ( 0 != ret )
  18.         {
  19.                 printf("Create pthread error!\n");
  20.                 exit(1);
  21.         }
  22.         for ( i = 0; i < 3; ++i )
  23.         {
  24.                 printf("this is the main process. \n");
  25.                 pthread_join( id, NULL );
  26.         }
  27.         /*pthread_timedjoin_np();*/

  28.         return 0;
  29. }
复制代码
同样的一个代码,我用
gcc test.c -lpthread
编译通过,运行也ok

但是使用
g++ test.c -lpthread
却报错为
example1.c: In function ‘int main()’:
example1.c:20: error: invalid conversion from ‘void*’ to ‘void* (*)(void*)’
example1.c:20: error:   initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’

请问原因为何?

还请问下有什么多线程编程的好资料推荐

谢谢

作者: alexandnpu   发布时间: 2010-08-23

  1. void thread( void )
复制代码
改为
  1. void* thread( void * p )
复制代码

作者: jackin0627   发布时间: 2010-08-23

C++对类型检测严格一些

作者: tajial   发布时间: 2010-08-23

沙发是正确的

作者: jnjn999   发布时间: 2010-08-23

回复 jackin0627


    还是不行啊,g++还是报出相同的错

我的g++是4.4.4 Fedora 13 的系统

作者: alexandnpu   发布时间: 2010-08-23

  1. void thread( void )
复制代码
改成
  1. void* thread( void* p )
复制代码
  1. ret = pthread_create( &id, NULL, (void *)thread, NULL );
复制代码
改成
  1. ret = pthread_create( &id, NULL, thread, NULL );
复制代码

作者: jackin0627   发布时间: 2010-08-23

回复 jackin0627


    我把
  1. #


  2. #         ret = pthread_create( &id, NULL, (void *)thread, NULL );
复制代码
改为
  1. #


  2. #         ret = pthread_create( &id, NULL, thread, NULL );
复制代码
之后就ok了,
那thread函数本身就是返回void *的,我多此一举的在pthread_create函数中轻质转换(void *),为什么会报错呢?

给个解释吧

作者: alexandnpu   发布时间: 2010-08-23

或直接将
  1. ret = pthread_create( &id, NULL, (void *)thread, NULL );
复制代码
改为
  1. ret = pthread_create( &id, NULL, (void * (*)(void*))thread, NULL );
复制代码

作者: jackin0627   发布时间: 2010-08-23



QUOTE:
回复  jackin0627


    我把改为之后就ok了,
那thread函数本身就是返回void *的,我多此一举的在pth ...
alexandnpu 发表于 2010-08-23 16:26


前面的错误代码解释的很清楚了
invalid conversion from ‘void*’ to ‘void* (*)(void*)’
这两个类型不兼容。。
建议搜索下 C语言函数指针的相关内容

作者: davelv   发布时间: 2010-08-23

回复 davelv


    嗯,刚看明白了,原来的那个thread本身是个函数指针,已经符合参数要求了,我加了一个(void *),以为是匹配了参数,实际上是把一个函数指针转换成了void* 指针,所以编译器会报出那样的错误

谢谢各位指点

作者: alexandnpu   发布时间: 2010-08-23