多线程程序+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();
扫描二维码关注公众号,回复: 3794083 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_38907330/article/details/82844876
今日推荐