c++多線程運行錯誤:terminate called without an active exception(運行錯誤)

#include <iostream>
#include <vector>
#include <ctime>
#include <thread>

template <typename container>
void print_container(container& con){
	typename container::iterator it = con.begin();
	for (; it != con.end(); ++it){
		std::cout << *it << "  ";
	}
	std::cout << std::endl;
}

void thread_fun(std::vector<int> &vec){
	print_container(vec);
}

int main(){
	std::vector<int> vec;
	srand(time(nullptr));//以系統時間爲隨機數種子
	for (int i = 0; i < 20; ++i){
		vec.push_back(rand()%100+1);
	}
	std::thread t1(thread_fun,std::ref(vec));
	t1.join();
	return 0;
}

其中t1.join()的作用是:主線程等待子線程運行結束,然後主線程纔會繼續往下運行。

可以通過該方法使得多線程順序執行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章