当前位置:网站首页>17.4 creating multiple threads, data sharing problem analysis and case code
17.4 creating multiple threads, data sharing problem analysis and case code
2022-06-11 11:22:00 【zzyzxb】
One 、 Creating and waiting for multiple threads
// Thread entry function
void myprint(int inum)
{
cout << "myprint The thread begins to execute , The thread number id=" << inum << endl;
printf("myprint The thread begins to execute , The thread number id=%d \n", inum);
//... Do all kinds of things
cout << "myprint The thread ended execution , The thread number id=" << inum << endl;
printf("myprint The thread ended execution , The thread number id=%d \n", inum);
return;
}
int main()
{
vector<thread> mythreads;
// establish 10 Threads , Thread entry functions are used uniformly myprint
for (int i = 0; i < 10; ++i)
{
mythreads.push_back(thread(myprint, i)); // establish 10 Threads , At the same time it 10 Threads have started executing
}
for (auto iter = mythreads.begin(); iter != mythreads.end(); iter++)
{
iter->join(); // wait for 10 Both threads return
}
cout << "main End of main function execution " << endl; // Finally, execute this sentence , The whole process exits
return 0;
}
establish 10 Threads , Thread entry functions are used uniformly myprint
<1> The execution order of multiple threads is disordered , It is related to the internal thread scheduling mechanism of the operating system ;
<2> The main thread waits for all child threads to finish running , Finally, the main thread ends ; The teacher recommended join Writing , It is easier to write stable programs ;
<3> We put thread Objects are put into containers for management , It looks like a thread Array , This is very convenient for us to create a large number of threads at one time and manage a large number of threads .
Two 、 Analysis of data sharing
vector<int> g_v = { 1,2,3 }; // Shared data , read-only
// Thread entry function
void myprint(int inum)
{
cout << "id = " << this_thread::get_id() << "gv Value = " << g_v[0] << g_v[1] << g_v[2] << endl;
return;
}
int main()
{
vector<thread> mythreads;
// establish 10 Threads , Thread entry functions are used uniformly myprint
for (int i = 0; i < 10; ++i)
{
mythreads.push_back(thread(myprint, i)); // establish 10 Threads , At the same time it 10 Threads have started executing
}
for (auto iter = mythreads.begin(); iter != mythreads.end(); iter++)
{
iter->join(); // wait for 10 Both threads return
}
cout << "main End of main function execution " << endl; // Finally, execute this sentence , The whole process exits
return 0;
}
<1> Read only data : It's safe and stable , No special treatment is required , Just read it directly ;
<2> Read and write :2 Threads write ,8 Thread reads , If the code doesn't handle it specifically , That program must crash ;
The simplest way to deal with it is not to crash , I can't write when I read , You can't read while you're writing .2 Threads cannot write at the same time ,8 Threads cannot read at the same time ;
The action of writing is divided into 10 half step ; Due to task switching , Leading to all kinds of weird things ( The most likely bizarre thing is collapse );
<3> Other cases
Data sharing Booking problem
3、 ... and : Practical examples of shared data protection
Online game server , Two self created threads , A thread collects player commands ( Use a number to represent the command sent by the player ), And write the command data to a queue .
Another thread takes the command sent by the player from the queue , analysis , Then perform the actions the player needs ;
vector and list
list: Frequent sequential insertion and deletion of data with high timeliness .
vector: The container randomly inserts and deletes data, which is highly efficient .
Prepare to use member functions as thread functions to write threads
class MA
{
public:
// Take the message you've received ( Player orders ) Threads put into a queue
void inMsgRecvQueue()
{
for (int i = 0; i < 100000; ++i)
{
cout << "inMsgRecvQueue() perform , Insert an element : " << i << endl;
msgRecvQueue.push_back(i); // Suppose this number i It's the order I received , Directly into the message queue
}
}
// Take the data of the thread from the queue
void outMsgRecvQueue()
{
for (int i = 0; i < 100000; ++i)
{
if (!msgRecvQueue.empty())
{
// The message is not empty
int command = msgRecvQueue.front(); // Returns the first element , But don't check if the element exists ;
msgRecvQueue.pop_front(); // Remove the first element , But not back
// Here, consider processing data ...
//...
}
else
{
// Message queue is empty
cout << "outMsgRecvQueue() perform , But at present, the message queue is empty " << i << endl;
}
}
cout << "end" << endl;
}
private:
list<int> msgRecvQueue; // Containers ( Message queue ), It is used to send commands on behalf of players
};
int main()
{
MA myobj;
std::thread myOutMsgObj(&MA::outMsgRecvQueue, &myobj); // The second parameter is the reference , To ensure that the same object is used in the thread
std::thread myInMsgObj(&MA::inMsgRecvQueue, &myobj);
myOutMsgObj.join();
myInMsgObj.join();
cout << "main End of main function execution " << endl; // Finally, execute this sentence , The whole process exits
return 0;
}
Code to solve problems : The introduction of a c++ The first concept to solve the problem of multi-threaded protection of shared data " The mutex ", Memorize the word in your head .
边栏推荐
猜你喜欢

(key points of software engineering review) Chapter IV overall design exercises
![my.cnf中 [mysql]与[mysqld] 的区别 引起的binlog启动失败的问题](/img/bd/a28e74654c7821b3a9cd9260d2e399.png)
my.cnf中 [mysql]与[mysqld] 的区别 引起的binlog启动失败的问题

李飞飞:我更像物理学界的科学家,而不是工程师|深度学习崛起十年

Introduction to thread pool: ThreadPoolExecutor

Typeerror: argument of type "Int 'is not Iterable

AI security and Privacy Forum issue 11 - stable learning: finding common ground between causal reasoning and machine learning

外观模式--在各种套餐中早就用到啦!

Exness: the progress of Russia Ukraine negotiations is limited, and the RBA's decision remains unchanged

MyCat-分库分表

Display of receiving address list 【 project mall 】
随机推荐
企业微信小程序避坑指南,欢迎补充。。。
SurroundDepth:自监督多摄像头环视深度估计
Iterator mode -- battlefield autumn point
使用pydub修改wav文件的比特率,报错:C:\ProgramData\Anaconda3\lib\site-packages\pydub\utils.py:170: RuntimeWarning:
WordPress登录页面美化插件:Login Designer推荐
Don't be a fake worker
What is the best annuity insurance product in 2022?
VOC格式数据集转yolo格式数据集的方法
不做伪工作者
【碎碎念】关于波长|波速|周期的想法
File excel export
WordPress数据库缓存插件:DB Cache Reloaded
在WordPress媒体库中创建文件夹
UCI-HAR数据集的处理
985 University doctors became popular because of their thanks in classical Chinese! The tutor commented that he not only wrote well in sci
Droid-slam: depth vision slam for monocular and binocular rgbd cameras
外观模式--在各种套餐中早就用到啦!
Introduction and usage of Eval function
WordPress regenerate featured image plugin: regenerate thumbnails
全国多年太阳辐射空间分布数据1981-2022年、气温分布数据、蒸散量数据、蒸发量数据、降雨量分布数据、日照数据、风速数据