C++ 无法使用线程实现列表操作
我是新手。在下面的代码中,我想使用一个线程将元素添加到全局列表中,并使用另一个线程搜索随机元素C++ 无法使用线程实现列表操作,c++,multithreading,C++,Multithreading,我是新手。在下面的代码中,我想使用一个线程将元素添加到全局列表中,并使用另一个线程搜索随机元素 #include <list> #include <algorithm> #include <mutex> #include <thread> using namespace std; list<int> some_list; mutex some_mutex; void add_to_list(int new_value) {
#include <list>
#include <algorithm>
#include <mutex>
#include <thread>
using namespace std;
list<int> some_list;
mutex some_mutex;
void add_to_list(int new_value)
{
lock_guard<mutex> guard(some_mutex);
some_list.push_back(new_value);
}
bool list_contains(int value_to_find)
{
lock_guard<mutex> guard(some_mutex);
return find(begin(some_list), end(some_list), value_to_find) != end(some_list);
}
int main()
{
for(int i = 0; i < 100; ++i)
{
// Add i to some_list through one thread only
thread t(add_to_list, i);
t.detach();
// Search elements in different thread
thread t2(list_contains, i);
t2.detach();
}
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
列出一些清单;
互斥一些互斥;
void add_to_list(int new_值)
{
锁定保护(一些互斥);
一些\u列表。将\u向后推(新的\u值);
}
布尔列表包含(要查找的int值)
{
锁定保护(一些互斥);
返回find(开始(一些列表)、结束(一些列表)、值到查找)!=end(一些列表);
}
int main()
{
对于(int i=0;i<100;++i)
{
//仅通过一个线程将i添加到某些_列表
线程t(将_添加到_列表中,i);
t、 分离();
//在不同的线程中搜索元素
线程t2(列表_包含,i);
t2.分离();
}
返回0;
}
然而,当我将I和add_一起传递到_列表时,就会创建很多线程。我只想使用单线程将元素添加到列表中。如何做到这一点?我需要将元素的向量而不是变量传递给线程吗?首先,不要使用
detach()
。在上面的代码中,程序启动200个线程并结束(当main()
返回时),而不等待任何线程完成。使用join()
然后,如果您希望按顺序向列表添加,请在单独的循环中执行
例如:
int main() {
vector<thread> threads;
// Add i to some_list through one thread only
threads.emplace_back([] {
for (int i = 0; i < 100; ++i) {
add_to_list(i);
}
});
for (int i = 0; i < 100; ++i) {
// Search elements in different threads
threads.emplace_back([i] {
list_contains(i);
});
}
// Join all threads (waits for their completion)
for (auto& t : threads) {
t.join();
}
}
intmain(){
向量线程;
//仅通过一个线程将i添加到某些_列表
线程。将_向后放置([]{
对于(int i=0;i<100;++i){
将_添加到_列表(i);
}
});
对于(int i=0;i<100;++i){
//在不同的线程中搜索元素
线程。将_放回([i]{
清单(i);;
});
}
//加入所有线程(等待其完成)
用于(自动&t:线程){
t、 join();
}
}