代码示例:
#include <iostream>
#include <thread>
#include <string>
using namespace std;
void show(string msg)
{
cout << "msg:"<<msg << endl;
for (int i = 0; i < 1000; i++)
{
cout << "i:" << i << endl;
}
return;
}
int main()
{
//1、创建线程
thread myThread(show,"进入线程");
myThread.join();//主线程会等待子线程结束后再结束
myThread.detach();//主线程不会等待子线程是否结束
this_thread::sleep_for(chrono::microseconds(1));//线程睡眠
system("pause");
return 0;
}
线程中传入引用类型的参数
#include <iostream>
#include <thread>
using namespace std;
void foo(int &x) {
}
int main()
{
int value = 1;
thread myThread1(foo, ref(value));//传递引用类型的数据
system("pause");
return 0;
}
线程中传入指针类型,可以考虑使用智能指针,可以自动释放。
#include <iostream>
#include <thread>
#include <string>
#include <memory>
#include<mutex>
using namespace std;
void f1(shared_ptr<int> x) {
cout << *x << endl;
}
int main()
{
//智能指针,当不在使用时,操作系统会自动释放
shared_ptr<int> a1 = make_shared<int>(1);
thread myThread3(f1,a1);
myThread3.join();
system("pause");
return 0;
}
信号量
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
std::mutex g_mutex;
std::condition_variable g_cv;
std::queue<int> g_queue;
void Producer() {
for (int i = 0; i < 10; i++) {
{
std::unique_lock<std::mutex> lock(g_mutex);//由于下方消费者也在操作g_queue,所以需要加互斥锁
g_queue.push(i);
std::cout << "Producer: produced " << i << std::endl;
}
g_cv.notify_one();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
void Consumer() {
while (true) {
std::unique_lock<std::mutex> lock(g_mutex);
//auto isbool = []()->bool {return !g_queue.empty(); };
//g_cv.wait(lock, isbool);//第二个参数如果是true,则会继续阻塞,否则不再阻塞,如果没有第二个参数,则第二个参数就是false
g_cv.wait_for(lock, std::chrono::milliseconds(100), []() {//阻塞100毫秒后,便会解除阻塞,注意第三个参数和wait相反
if (g_queue.empty())
{
cout << "队列为空" << endl;
return false;
}
else
{
cout << "队列不为空" << endl;
return true;
}
});
if (!g_queue.empty())
{
int value = g_queue.front();
g_queue.pop();
std::cout << "Consumer: consumed " << value << std::endl;
}
else
{
cout << "队列依旧为空" << endl;
}
}
}
int main() {
std::thread producer_thread(Producer);
std::thread consumer_thread(Consumer);
producer_thread.join();
consumer_thread.join();
return 0;
}