use*_*897 2 c++ multithreading pthreads
我如何发送std::string到我的线程?
这是我的代码:
void* sendReminder(void*)
{
system("echo 'hello' >> buffer.txt");
}
int main()
{
string str1 = "somevalue";
pthread_t t1;
pthread_create(&t1, NULL, &sendReminder, NULL);
}
Run Code Online (Sandbox Code Playgroud)
使用第四个参数来pthread_create向函数发送"参数",只需确保在堆上复制它:
string *userData = new string("somevalue");
pthread_create(&t1, NULL, &sendReminder, (void *) userData);
Run Code Online (Sandbox Code Playgroud)
如果您将pthread_join等待新线程,暂停执行调用程序,您只需传递局部变量的地址即可:
if (pthread_create(&t1, NULL, &sendReminder, (void *) &str1) == 0)
{
pthread_join(t1, &result);
// ...
Run Code Online (Sandbox Code Playgroud)
您可以使用以下方法检索值:
void* sendReminder(void* data)
{
std::string* userData = reinterpret_cast<std::string*>(data);
// Think about wrapping `userData` within a smart pointer.
cout << *userData << endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2533 次 |
| 最近记录: |