std::thread charge_thread(agv_charge, i);,非標準語法,使用&建立成員指標
时间: 2023-11-30 17:15:34 浏览: 29
对的,如果你想使用成员指针作为线程函数的参数,可以使用`std::thread`构造函数的第一个参数来传递该指针。例如,如果`agv_charge`是一个成员函数,你可以通过以下方式创建一个线程:
```
MyClass obj;
std::thread charge_thread(&MyClass::agv_charge, &obj, i);
```
其中,`&MyClass::agv_charge`是成员函数的指针,`&obj`是该成员函数所属的对象的指针,`i`是该成员函数的参数。
注意,成员指针需要使用`&`取地址符来获取其指针值。另外,由于成员函数需要通过对象来访问其成员变量,因此需要将对象的指针传递给线程函数作为第二个参数。
相关问题
std::thread t(agv_charge(i)); t.detach();
这段代码中,创建了一个名为t的线程,并将函数agv_charge(i)作为参数传递给它。然后,使用detach()函数将线程与主线程分离,使它们可以同时执行。这意味着主线程不会等待t线程完成,而是继续执行自己的任务。因此,如果agv_charge(i)函数需要访问共享资源,必须使用互斥量或其他同步机制来避免竞争条件。
void assign_task_to_agv(std::vector<Task>& tasks, std::vector<AGV>& agvs);怎麽修改: threads.push_back(std::thread(&AGVScheduler::assign_task_to_agv, std::vector<Task>& tasks, std::vector<AGV>& agvs));
在创建新的线程时,需要将函数的参数直接传递给 `std::thread` 构造函数,不需要在参数类型前面加上参数名。因此,正确的写法应该是:
```
threads.push_back(std::thread(&AGVScheduler::assign_task_to_agv, std::ref(tasks), std::ref(agvs)));
```
这样就可以将 `tasks` 和 `agvs` 作为参数传递给 `AGVScheduler::assign_task_to_agv` 函数,并在新的线程中运行该函数。注意,这里使用了 `std::ref` 来将 `tasks` 和 `agvs` 引用传递给线程,避免了拷贝。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)