近日项目需要用到多线程,由于之前没有写过c++代码,经过研究,发现c++11引入了一个多线程类,就写了一个简单的例子,做个简单记录。 –2018年的今天很冷,全球股市暴跌。
简单多线程例子:
detch()启动线程:
#include <thread>
#include <Windows.h>
using namespace std;
void TestThread1();
void TestThread2();
int main(){
thread t1(TestThread1);
t1.detach();
thread t2(TestThread2);
t2.detach();
printf("主线程:你好帅!!!!\n");
system("pause");
}
void TestThread1(){
for (int i = 0; i < 10; i++){
printf("TestThread1:%d\n", i);
Sleep(100);
}
}
void TestThread2(){
for (int i = 100; i < 110; i++){
printf("TestThread2:%d\n", i);
Sleep(100);
}
}
说明:detch()方法的意思就是开启子线程,并且主线程不等待子线程运行完毕,而是和子线程并行运行。
运行结果:
join()方法启动线程:
#include <thread>
#include <Windows.h>
using namespace std;
void TestThread1();
void TestThread2();
int main(){
thread t1(TestThread1);
t1.join();
thread t2(TestThread2);
t2.join();
printf("主线程:你好帅!!!!\n");
system("pause");
}
void TestThread1(){
for (int i = 0; i < 10; i++){
printf("TestThread1:%d\n", i);
Sleep(100);
}
}
void TestThread2(){
for (int i = 100; i < 110; i++){
printf("TestThread2:%d\n", i);
Sleep(100);
}
}
说明:join()方法的意思就是开启子线程,线程会按照开启的先后顺序同步运行。
运行结果:
子线程函数带有参数的多线程:
#include <thread>
#include <Windows.h>
using namespace std;
void TestThread1(int count);
void TestThread2(int start ,int count);
int main(){
thread t1(TestThread1,10);
t1.detach();
thread t2(TestThread2,40,50);
t2.detach();
printf("主线程:你好帅!!!!\n");
system("pause");
}
void TestThread1(int count){
for (int i = 0; i < count; i++){
printf("TestThread1:%d\n", i);
Sleep(100);
}
}
void TestThread2(int start,int count){
for (int i = start; i < count; i++){
printf("TestThread2:%d\n", i);
Sleep(100);
}
}
运行结果:
多线程安全访问共享数据例子(卖票)
ThreadTest.h头文件
#ifndef _THREAD_TEST_H_
#define _THREAD_TEST_H_
#include <stdio.h>
#include <thread>
#include <mutex>
#include <Windows.h>
using namespace std;
class ThreadTest
{
public:
//卖票线程1
void ThreadTest::Thread1();
//卖票线程2
void ThreadTest::Thread2();
ThreadTest();
~ThreadTest();
private:
//票的剩余数目
int Sum;
mutex Mutex;//线程锁
};
#endif // !_THREAD_TEST_H_
ThreadTest.cpp 文件
#include "ThreadTest.h"
using namespace std;
void ThreadTest::Thread1(){
for (;;){
Mutex.lock();//加锁
Sleep(10);
--Sum;
if (Sum < 0){
printf("Thrad1——票卖完了\n", Sum);
break;
}
printf("Thrad1——剩余票数:%d\n", Sum);
Mutex.unlock();//解锁
}
Mutex.unlock();//解锁
}
void ThreadTest::Thread2(){
for (;;){
Mutex.lock();//加锁
Sleep(10);
--Sum;
if (Sum < 0){
printf("Thrad2——票卖完了\n");
break;
}
printf("Thrad2——剩余票数:%d\n", Sum);
Mutex.unlock();//解锁
}
Mutex.unlock();//解锁
}
//构造函数
ThreadTest::ThreadTest()
{
Sum = 50;
thread t1(&ThreadTest::Thread1,this);
t1.detach();
thread t2(&ThreadTest::Thread2,this);
t2.detach();
}
//析构函数
ThreadTest::~ThreadTest()
{
}
mian函数
#include "ThreadTest.h"
int main(){
//多线程卖票类
ThreadTest SaleThread;
while (true){
//为了截图方便--加入死循环
}
}
运行结果:
说明:对于线程锁的使用可参考博客c++11线程锁的使用
希望对您有所帮助!