Linux C编程求大神帮忙,感激不尽

gstatham 2016-02-18 05:59:53


void Detect_4G_model(void *param)
{
while(1) {
/ 检测到插入模块 */
g_4g_status = RUN;

/* 检测到拔出模块 */
g_4g_status = STOP;
}

}
void Send_to_4g_thread(void *param)
{
/ 下面是需要挂起和唤醒的部分*/
while(1) {

/* .... */
}

return NULL;
}

int main(int argc, char * argv[])
{
pthread_create(&tid1, NULL, Detect_4G_model, NULL);
pthread_create(&tid2, NULL, Send_to_4g_thread, NULL);
}
程序有两个线程,线程td1用来检测外部模块的插入和拔出,当检测到拔出时,g_4g_status 设置为 STOP;当检测到插入时,g_4g_status 设置为RUN, 请问,怎么根据g_4g_status 的状态来控制线程Send_to_4g_thread的挂起和唤醒,最好写出点代码,O(∩_∩)O谢谢
...全文
193 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
csdn_vieri 2016-02-18
  • 打赏
  • 举报
回复
拿去,不谢。
#include <pthread.h>
#include <stdio.h>

#define RUN  1
#define STOP 0

bool g_4g_status = STOP;

pthread_mutex_t g_status_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_status_cond = PTHREAD_COND_INITIALIZER;

void * Detect_4G_mode(void * param)
{
    while (1)
    {
        pthread_mutex_lock(&g_status_mutex);
        g_4g_status = RUN;
        pthread_cond_signal(&g_status_cond);
        pthread_mutex_unlock(&g_status_mutex);

        pthread_mutex_lock(&g_status_mutex);
        g_4g_status = STOP;
        pthread_mutex_unlock(&g_status_mutex);
    }

    return NULL;
}

void * Send_to_4g_thread(void * param)
{
    while(1)
    {
        pthread_mutex_lock(&g_status_mutex);
        while (STOP == g_4g_status)
        {
            pthread_cond_wait(&g_status_cond, &g_status_mutex);
        }
        pthread_mutex_unlock(&g_status_mutex);

        /*....*/
    }

    return NULL;
}

int main(int argc, char * argv[])
{
    pthread_t tid1;
    pthread_t tid2;

    pthread_create(&tid1, NULL, Detect_4G_mode, NULL);
    pthread_create(&tid2, NULL, Send_to_4g_thread, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    return 0;
}
qq_31930857 2016-02-18
  • 打赏
  • 举报
回复
诶…还没学到那呢……要不我肯定给你解决下
gstatham 2016-02-18
  • 打赏
  • 举报
回复
给自己顶一下

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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