线程间通信问题求教

gstatham 2017-09-04 02:12:41
全局变量结构体 netControl;

线程A:

while(netControl.isRuning)
{
//do something
}

线程B:用来控制线程A

收到事件A,则执行 netControl.isRuning = 0;
收到事件B,则执行 netControl.isRuning = 1;


现在问题是,事件A可以使线程A的内容不执行,但是事件B无法使线程A的内容继续执行,这样的设计有问题么?
...全文
216 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
821586284 2017-09-05
  • 打赏
  • 举报
回复
http://blog.csdn.net/yeyuangen/article/details/37593533 参考这篇文章
呔妖怪来嘛 2017-09-05
  • 打赏
  • 举报
回复
最好的实现方式是收到事件B创建A线程,收到事件A删除A线程,耦合不会太严重
gstatham 2017-09-05
  • 打赏
  • 举报
回复
感谢各位的回答,自己给出一套解决方案
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

pthread_t IDA;
pthread_t IDB;

pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

#define RUN 1
#define STOP 0

int status = RUN;

void * thread_function(void *param)
{
    static int i = 0;
    while (1)
    {
        pthread_mutex_lock(&mut);
        while (!status)
        {
            pthread_cond_wait(&cond, &mut);
        }
        pthread_mutex_unlock(&mut);

        //do actual something
        printf("thread is running...\n");
        sleep(1);
    }
}

void thread_resume()
{
    if (status == STOP)
    {
        pthread_mutex_lock(&mut);
        status = RUN;
        pthread_cond_signal(&cond);
        printf("pthread run!\n");
        pthread_mutex_unlock(&mut);
    }
}

void thread_pause()
{
    if (status == RUN)
    {
        pthread_mutex_lock(&mut);
        status = STOP;
        printf("thread stop!\n");
        pthread_mutex_unlock(&mut);
    }
}

void *test(void *param)
{
    while(1)
    {
        sleep(5);
        thread_pause();
        sleep(10);
        thread_resume();
        sleep(5);
    }
}


int main(int argc, char *argv[])
{
    pthread_create(&IDA, NULL, test, NULL);
    pthread_create(&IDB, NULL, thread_function, NULL);

    pthread_join(IDA, NULL);
    pthread_join(IDB, NULL);

    return 0;
}
paschen 版主 2017-09-04
  • 打赏
  • 举报
回复
建议中断下来看线程断在了哪再分析原因
gstatham 2017-09-04
  • 打赏
  • 举报
回复
线程A不会不存在的,事件A发生时,线程A只是没有进入while的循环
rayw0ng 2017-09-04
  • 打赏
  • 举报
回复
设计没问题。 问题是事件A会结束while循环,然后会结束线程A。再到事件B的时候线程A已经不存在了,这个时候需要重新创建线程A。

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧