回调函数及线程的使用
一、在QT下使用C11的函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #pragma once 2 //C11的方法 3 #include <thread> // std::thread, std::this_thread::sleep_for 4 #include <chrono> // std::chrono::seconds 5 6 typedef struct _point 7 { 8 _point() 9 { 10 nX = 0; 11 nY = 0; 12 } 13 int nX; 14 int nY; 15 }POIINT, *PPOIINT; 16 17 typedef void(*UPDAPOINTCALLBACK)(POIINT* point, void* pDlg); 18 19 class ThreadAndCall 20 { 21 public: 22 ThreadAndCall(); 23 ~ThreadAndCall(); 24 public: 25 void setupUpdateGUICallback(UPDAPOINTCALLBACK callback, void* pDlg); 26 void StartThread(); 27 private: 28 UPDAPOINTCALLBACK updatePointCallback; 29 void* pDlg; 30 private: 31 static void funcThread(ThreadAndCall *pThis); 32 private: 33 34 };
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include "ThreadAndCall.h" #include <mutex> using namespace std; mutex g_lock; //全局互斥锁对象 ThreadAndCall::ThreadAndCall() { } ThreadAndCall::~ThreadAndCall() { } void ThreadAndCall::setupUpdateGUICallback(UPDAPOINTCALLBACK callback, void* pDlg) { this->updatePointCallback = callback; this->pDlg = pDlg; } void ThreadAndCall::StartThread() { thread t1(funcThread, this); t1.detach(); //t1.join(); } void ThreadAndCall::funcThread(ThreadAndCall *pThis) { POIINT point; for (int i = 0; i < 10000; i++) { //g_lock.lock(); //上锁 这个程序加不加都可以 point.nX = i; point.nY = i; pThis->updatePointCallback(&point, pThis->pDlg); printf("%d--%d\n",i,i); this_thread::sleep_for(chrono::seconds(2)); //g_lock.unlock(); //解锁 } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1.======================= private slots: void on_threadcallBtn_clicked(); private: void static updatePoitGUI(POIINT* point, void* pDlg); 2.======================= void BaseDemo::on_threadcallBtn_clicked() { printf("=================================ThreadAndCall===============================\n"); pTestThreadAndCall = new ThreadAndCall(); pTestThreadAndCall->setupUpdateGUICallback(updatePoitGUI, this); pTestThreadAndCall->StartThread(); } void BaseDemo::updatePoitGUI(POIINT* point, void* pDlg) { BaseDemo *pWindow = (BaseDemo *)pDlg; QString str; str = QString("X:%1,Y:%2").arg(point->nX).arg(point->nY); pWindow->ui.showLable->setText(str); //this_thread::sleep_for(chrono::seconds(10)); }