微凉的衣柜 2020-11-03 23:58 采纳率: 64.7%
浏览 203
已采纳

C++ thread类遇到c2672和c2893错误

在调试一个比较简答的线程类程序,代码如下:

#include<iostream> 
#include<thread> 
#include <chrono>
#include<string>
using  namespace  std;
//命名空间this_thread有所有的线程辅助函数  get_id()   yield()  sleep_for()   sleep_until
using namespace std::this_thread;

//命名空间chrono有seconds模板类、milliseconds模板类
using  namespace  std::chrono;

void   ThreadFun(string   &str);

int  main()
{
    thread t1(ThreadFun, string("rtt"));//此处在给线程传参数时出错
    cout << t1.get_id() << endl;

    //等待子线程完成
    t1.join();

    return 0;
}


void   ThreadFun(string   &str)
{
    cout << "线程ID:" << get_id() << endl;//获取线程ID

    while (true)
    {
        cout << str << endl;
        sleep_for(seconds(1));//让线程睡眠1秒

        yield();//让线程睡眠一个极小的时间片,给其他线程执行

        sleep_until(system_clock::now() + milliseconds(1000));//让线程睡眠当前时间+1秒

    }

}


代码会出现以下错误:
图片说明

如果将线程函数改为非引用传参:

void   ThreadFun(string   str);

则不会出现错误,修改后代码如下:

#include<iostream> 
#include<thread> 
#include <chrono>
#include<string>
using  namespace  std;
//命名空间this_thread有所有的线程辅助函数  get_id()   yield()  sleep_for()   sleep_until
using namespace std::this_thread;

//命名空间chrono有seconds模板类、milliseconds模板类
using  namespace  std::chrono;

void   ThreadFun(string   str);

int  main()
{
    thread t1(ThreadFun, "rtt");
    cout << t1.get_id() << endl;

    //等待子线程完成
    t1.join();

    return 0;
}

void   ThreadFun(string   str)
{
    cout << "线程ID:" << get_id() << endl;//获取线程ID

    while (true)
    {
        cout << str << endl;
        sleep_for(seconds(1));//让线程睡眠1秒

        yield();//让线程睡眠一个极小的时间片,给其他线程执行

        sleep_until(system_clock::now() + milliseconds(1000));//让线程睡眠当前时间+1秒

    }

求各位分析。

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-20 23:45
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已采纳回答 12月7日

悬赏问题

  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?