现在的位置: 首页 > 综合 > 正文

C++ 中使用pthread_create的问题

2013年10月07日 ⁄ 综合 ⁄ 共 679字 ⁄ 字号 评论关闭
在c语言中使用pthread_create的常用方法为

  1. #include
    <stdio.h>
  2. #include
    <stdlib.h>
  3. #include
    <pthread.h>
  4. void*
    hello() {
  5. printf("helloworld\n");
  6. }
  7. intmain()
    {
  8. pthread_t pid;
  9. pthread_create(&pid, NULL,
    hello, NULL);
  10. sleep(1);
  11. return1;
  12. }
  13. //gcc -o test
    -g -Wall -lpthread test.c

这样就可以了

但是这样的代码在c++ 中却报错不能编译通过

经过向hightman请教得知在c++中函数的参数是和函数一起进行编译的,这样做的目的为了解决同名函数的重载,所以必须要吧上边的程序修改一下

  1. #include
    <stdio.h>
  2. #include
    <stdlib.h>
  3. #include
    <pthread.h>
  4. void*
    hello(
    void*arg)
    {
  5. printf("helloworld\n");
  6. returnNULL;
  7. }
  8. intmain()
    {
  9. pthread_t pid;
  10. pthread_create(&pid, NULL,
    hello, NULL);
  11. sleep(1);
  12. return1;
  13. }
  14. //g++ -o test
    -g -Wall -lpthread test.c

这样就可以编译通过了

第二个问题也是pthread_create 的问题

在使用类成员函数作为回调函数时也会出现上边类似的情况,这个情况的解决办法网上的说法比较传统的是把这个类成员函数定义为const的就可以了

抱歉!评论已关闭.