簡體   English   中英

類中使用pthreads時出現分段錯誤

[英]segmentation fault while using pthreads in class

我有以下代碼會導致核心轉儲錯誤。 每個C實例都會創建自己的線程,然后運行。 我猜靜態函數和類參數“ count”有問題。 當我注釋掉打印它的代碼時,沒有錯誤發生。

 #include <iostream>
    #include <pthread.h>
    using namespace std;

    class C {
        public:
        int count;
        C(int c_): count(c_){}
    public:
        void *hello(void)
        {
            std::cout << "Hello, world!" <<std::endl;
            std::cout<<count; // bug here!!!
            return 0;
        }

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

        void run()  {

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

    };

    int main()  {

    C c(2);
    c.run();

    C c2(4);
    c2.run();

    while(true);

    return 0;
    }

決定寫一個答案。 您根據創建線程的方式使用NULL context調用hello_helper C ++完全允許您在空指針上調用成員函數,除非訪問成員元素,否則不會發生任何錯誤。

在您的情況下,通過將行添加到print count 現在,您正在訪問空指針上的成員變量,這是很大的禁止。

這是您所逃脫的示例:

#include <iostream>
class Rebel
{
    public:
    void speak()
    {
        std::cout << "I DO WHAT I WANT!" << std::endl;        
    }    
};
int main()
{
    void * bad_bad_ptr = NULL;
    ((Rebel*)bad_bad_ptr)->speak();
}

輸出:

I DO WHAT I WANT!

通過修改pthread_create調用以傳遞this指針(即pthread_create(&t, NULL, &C::hello_helper, this); ,您現在有了一個有效的實例來訪問成員變量。

我通過在創建線程時將此指針而不是NULL傳遞來解決了該問題。 我猜想os在前一種情況下兩次創建了相同的線程?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM