多线程程序+QT中定时器槽函数

进程:一个进程相当于一个程序,相互之间是独立的,一个进程可能同时拥有好多个线程,线程之间共享内存和代码。

在QT中构建多线程程序时,一般将每一个线程写成一个类,包含创建线程,启动线程,终止线程等:

//创建线程
 pthread_mutex_init(&m_MutexMatch,NULL);
 pthread_t a_thread;
 int res =pthread_create(&a_thread,NULL,MatchDataRun,this);
 if(res !=0)
    {
        printf("receiving thread create failed!!!!!!!!!!!!!!!!!!!!!!!!\n");
        return 0;
    }

下面是我用的类的格式,可以直接拿来用(只需要将线程的名字,调用函数改成与自己程序相适应的就行了):

.cpp

#include "MatchData.h"
#include <iostream>
#include "mainwindow.h"
using namespace  std;

void * MatchDataRun(void *arg);

MatchData::MatchData()
{
    m_runflag=false;
}

MatchData::~MatchData()
{
}


void MatchData::init(MainWindow *w)
{
    m_runflag=true;
    m_mainwindow=w;
}

int MatchData::StartThread()
{
    pthread_mutex_init(&m_MutexMatch,NULL);
    pthread_t a_thread;
    int res =pthread_create(&a_thread,NULL,MatchDataRun,this);
    if(res !=0)
    {
        printf("receiving thread create failed!!!!!!!!!!!!!!!!!!!!!!!!\n");
        return 0;
    }
    return 1;
}

void * MatchDataRun(void *arg)
{
    MatchData *command = (MatchData *)arg;
    command->StartRun();
}

void MatchData::StartRun()
{

    while(m_runflag)
    {
       m_mainwindow->updateflag();

       usleep(5);
    }
 //   pthread_mutexattr_destroy(&m_MutexMatch);
}

void MatchData::StopThread()
{
    m_runflag=false;
}

.hpp

#ifndef MATCHDATA_H
#define MATCHDATA_H
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include "math.h"

using namespace std;

class MainWindow;
class MatchData
{
public:
    void init(MainWindow * win);
    int  StartThread();
    void StopThread();
    void StartRun();

    MatchData();
    ~MatchData();
    bool m_runflag;


private:
    MainWindow * m_mainwindow;

protected:
    pthread_mutex_t m_MutexMatch;   //RRK
};

#endif // PCAP_H

如果线程中涉及到读写操作,可能需要添加读写锁(https://blog.csdn.net/weixin_40839342/article/details/81189596

                            QReadWriteLock lock;

 

 

定时器槽函数:

        QTimer *timer = new QTimer(&w);
        timer->setInterval(30);
        QObject::connect(timer, SIGNAL(timeout()), &w, SLOT(DetectCam()));
        timer->start();

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

syvge

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值