可以先看看這篇文章,介紹了thread這個class
在這篇文章,會介紹:
- 無回傳值、也無傳入參數
- 無回傳值、但有傳入參數
- 如何搭配class使用
先介紹第一種:無傳回值、也無傳入參數
#include <iostream>
#include <thread>
using namespace std;
void show()
{
//下面這兩行迴圈只是延遲用
for (int i = 1; i <= 10000; i++)
for (int j = 1; j <= 10000; j++)
;
cout << "World.";
}
int main()
{
thread t1(show);
cout << "Hello ";
t1.join();//等待t1執行完畢才繼續往下執行
cout << "\n\n\n";//跳三行
system("pause");
return 0;
}
執行結果如下
第二種:無回傳值、但有傳入參數,使用bind來達成。
#include <iostream>
#include <thread>
using namespace std;
void addAndShow(int a, int b, char* name)
{
//下面這兩行迴圈只是延遲用
for (int i = 1; i <= 10000; i++)
for (int j = 1; j <= 10000; j++)
;
cout << name << ":" << (a + b) << endl;
}
int main()
{
char name[] = "Number from Main";
thread t(bind(&addAndShow, 100, 50, name));
cout << "\n";
t.join();
system("pause");
return 0;
}
執行結果如下
最後一部分:搭配class使用,這個我會搭配openCV,一次播放兩部影片(openCV的部分則不會註解)
#include <iostream>
#include <future>
#include <opencv2\opencv.hpp>
using namespace std;
using namespace cv;
class VideoThread
{
private:
VideoCapture capture;
thread* t;//使用指標,需要使用時才new,更顯彈性
string windowName;
Mat frame;
long frameCount;
long startFrame;
bool stop;
int fps;
void show()
{
capture.set(CV_CAP_PROP_POS_FRAMES, startFrame);
while (stop == false)
{
if (capture.read(frame) == false)
{
stop = true;
continue;
}
resize(frame, frame, Size(frame.cols / 2, frame.rows / 2));
imshow(windowName, frame);
}
}
public:
VideoThread(string videoPath, string windowName)
{
VideoThread::windowName = windowName;
capture.open(videoPath);
if (capture.isOpened() == false)
{
stop = false;
frameCount = 0;
fps = 0;
}
else
{
frameCount = capture.get(CV_CAP_PROP_FRAME_COUNT);
fps = capture.get(CV_CAP_PROP_FPS);
startFrame = 0;
stop = false;
}
}
void setStartFrame(int frameNumber)
{
startFrame = frameNumber;
}
void PlayVideo()
{
t = new thread(&VideoThread::show, this);
}
void StopVideo()
{
stop = true;
}
bool isStopVideo()
{
return stop;
}
};
int main()
{
VideoThread video1("D:/Bad Apple!! PV.mp4", "Video 1");
VideoThread video2("D:/戀愛多一點.mp4", "Video 2");
video1.PlayVideo();
video2.setStartFrame(1000);
video2.PlayVideo();
while (video1.isStopVideo() == false || video2.isStopVideo() == false);
system("pause");
return 0;
}
執行結果如下