免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12
最近访问板块 发新帖
楼主: clyman
打印 上一主题 下一主题

[C++] linux下c++的thread问题 [复制链接]

论坛徽章:
0
11 [报告]
发表于 2006-11-15 09:36 |只看该作者
加static 是对的。

论坛徽章:
0
12 [报告]
发表于 2006-11-15 17:38 |只看该作者
从csdn上找来的答案,问题答案一样,解决办法不一样
楼上面的答案还是没编译过去,唉~~

#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;

class Thread
{
  private:
    int number;
    pthread_t tid[2];

  public:
    Thread()
    {
      number = 1;
      pthread_create(&tid[1], NULL, thread1_ex, this);
      pthread_create(&tid[2], NULL, thread2_ex, this);
    }

    ~Thread()
    {
      cout << "tid1 is " << tid[1] << " tid2 is " << tid[2] << endl;
      pthread_join(tid[1], NULL);
      pthread_join(tid[2], NULL);
    }

    static void* thread1_ex(void* pVoid)
    {
      Thread* p = (Thread*)pVoid;
      p->thread1();
      return p;
    }

    static void* thread2_ex(void* pVoid)
    {
      Thread* p = (Thread*)pVoid;
      p->thread2();
      return p;
    }

    void* thread1()
    {
      for(int i = 0; i < 10; i++)
      {
        cout << "this is thread1, number is " << number++;
        cout << " pid is " << getpid() << " id is " << pthread_self() << endl;
      }
    }

    void* thread2()
    {
      for(int i = 0; i < 10; i++)
      {
        cout << "this is thread2, number is " << number++;
        cout << " pid is " << getpid() << " id is " << pthread_self() << endl;
      }
    }
};

int main()
{
  Thread *th = new Thread();
  delete(th);

  return 0;
}

论坛徽章:
0
13 [报告]
发表于 2006-11-15 17:41 |只看该作者
原帖由 billzhou 于 2006-11-14 11:15 发表



忘了  函数体内改一下    nthis.number++就可以了

nthis->number++

论坛徽章:
0
14 [报告]
发表于 2006-11-16 09:24 |只看该作者
原帖由 clyman 于 2006-11-15 17:38 发表
从csdn上找来的答案,问题答案一样,解决办法不一样
楼上面的答案还是没编译过去,唉~~

#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
...


用g++-4.1编译过去但运行有问题
试想一下这种做法还是存在一定的问题,线程去访问一个对象,而这个对象在析构后消亡,
程序存在根本性错误,他以为通过纯种调用类的函数,但是没注意到调中类中函数和 C 中函数是不同的
调用类中函数需有类对象这个实体存在,而 C 中则不需要,因在 C 中函数只是一段代码的标识而已

无疑这种做法风险很大

[ 本帖最后由 chzht001 于 2006-11-16 09:31 编辑 ]

论坛徽章:
0
15 [报告]
发表于 2006-11-16 09:27 |只看该作者
原帖由 clyman 于 2006-11-15 17:41 发表

nthis->number++


这样是对的 呵呵 马虎了
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP