QNX c线程问题

QNX c线程问题,第1张

概述我有一个关于此代码的问题,我想在QNX上运行: class ConcreteThread : public Thread{public: ConcreteThread(int test) { testNumber = test; } void *start_routine() { for(int i = 0; i < 我有一个关于此代码的问题,我想在QNX上运行:

class ConcreteThread : public Thread{public:    ConcreteThread(int test)    {        testNumber = test;    }    voID *start_routine()     {         for(int i = 0; i < 10; i++)        {            sleep(1);            cout << testNumber << endl;        }       }private:    int testNumber;};class Thread {public:    Thread(){};    int Create()    {        pthread_t m_ID;        return pthread_create(&m_ID,NulL,&(this->start_routine_trampoline),this);    }protected:    virtual voID *start_routine() = 0;private:    static voID *start_routine_trampoline(voID *p)    {        Thread *pThis = (Thread *)p;        return pThis->start_routine();    }};

现在,当我在* start_routine中没有睡眠的情况下运行此代码时,它将简单地打印数字10次,然后继续下一行代码(顺序而不是并行).但是,当我在代码中使用睡眠时,它根本不打印任何数字,只是继续下一行代码.为什么不睡觉工作,我怎样才能创建这样的线程,而不是运行顺序?

解决方法 注1:如果您只有1个处理器,则无论您创建多少个线程,代码都只能按顺序执行.每个线程在换出下一个线程之前都会获得一段处理器时间.

注意2:如果主线程退出pthreads将在它们有机会执行之前终止所有子线程.

现在回答你的问题:

没有睡觉.线程一旦启动就有足够的时间在单个切片中给出完全执行循环10次.

随着睡眠:你的工作线程将睡一整秒.所以你的主线程有时间做很多工作.如果主线程在此时退出,则工作人员将被杀死.

我会做出以下更改:

//  Remove the Create() method//  Put thread creation in the constructor.//  Make the thread variable part of the objectpthread_t m_ID;Thread(){    if (pthread_create(&m_ID,this) != 0)    {        throw std::runtime_error("Thread was not created");    }}// Make sure the destructor waits for the thread to exit.~Thread(){    pthread_join(m_ID);}

如果你去看看增强线程库.你会发现像这样的所有小错误已经得到了照顾;从而使线程更易于使用.

另请注意.使用静态可能有效,但它不可移植.这是因为pthread是一个C库,因此期望一个带有C ABI的函数指针.您只是在这里为您的平台幸运.您需要将此定义为函数并使用extern“C”声明ABI

// This needs to be a standard function with C Interface.extern "C" voID *start_routine_trampoline(voID *p){}
总结

以上是内存溢出为你收集整理的QNX c线程问题全部内容,希望文章能够帮你解决QNX c线程问题所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1212375.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存