gpt4 book ai didi

c++ - pthread 从类访问它,变量丢失,直接工作正常

转载 作者:搜寻专家 更新时间:2023-10-31 01:54:16 25 4
gpt4 key购买 nike

好吧,我正在尝试设置一个变量以在线程中使用,如果我从主函数调用 pthread,它工作正常,但如果我从函数或类中的函数调用它,变量就会丢失而是打印垃圾,这就是我添加条件的原因

if(this->pickup < 7)

所以我最小化了代码,这样我就可以将它发布在这里,因为它包含了我所说的所有示例。

下面这段代码的输出是:

Access by Class:

Hello, world! <

Access Directly:

Hello, world!, N: 6<

我希望在按类访问中获得与直接访问中相同的结果,我希望它输出“, N: 6”,因为毕竟它已被定义。我在这里错过了什么?

我希望我已经足够清楚了,在此先感谢。

(顺便说一下,我使用的是适用于 windows 的 pthread 库)所以这是代码:

#include <stdio.h>
#include <pthread.h>
#include <iostream>
#include <conio.h>
#include <windows.h>

class C {
public:
int pickup;

void *hello()
{
std::cout << "\nHello, world!";

if(this->pickup < 7)
std::cout << ", N: " << this->pickup;

std::cout << "<" << std::endl;
printf("HI");
return 0;
}

static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}


void StartThread(){
C c;
c.pickup = 6;

pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
}


};



int main () {

C c;
std::cout << "Access by Class: \n";
c.StartThread();
c.pickup = 6;
Sleep(2000);

std::cout << "\nAccess Directly: \n";
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);

_getch();
return 0;
}

最佳答案

cStartThread() 返回时被销毁,这意味着 hello_helper() 使用悬空指针导致未定义的行为。

更改为:

void StartThread(){
C* c = new C();
c->pickup = 6;

pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, c);
}

记得删除传入hello_helper()的参数:

static void *hello_helper(void *context)
{
C* c = static_cast<C*>(context);
c->hello();
delete c;
return 0;
}

编辑:

始终删除传递给hello_helper() 的参数会阻止将堆栈分配的对象传递给hello_helper()。需要一种机制来指示 hello_helper() 是否负责破坏其参数。

关于c++ - pthread 从类访问它,变量丢失,直接工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9944517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com