簡體   English   中英

C++ 中的 pthread_create 錯誤(類內的 pthread)

[英]pthread_create error in C++ (pthread inside class)

我有這個 C++ 代碼,我嘗試在其中創建一個 pthread,但出現 4 個錯誤:

有人可以幫忙嗎?

提前致謝。

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

static void* func(void*);

class Test
{
 public:
    pthread_t *threadId;
    pthread_create(threadId, NULL, func, NULL);

 };

 static void* func(void *arg)
 {
   printf("Thread function called\n");
 }

 int main()
 {
  Test();
 }

編譯:

 # g++ simplepThread.cc -lpthread
      simplepThread.cc:11: error: ‘threadId’ is not a type
      simplepThread.cc:11: error: expected identifier before ‘__null’
      simplepThread.cc:11: error: expected ‘,’ or ‘...’ before ‘__null’
      simplepThread.cc:11: error: ISO C++ forbids declaration of ‘pthread_create’ with no type

如果我使用線程 function 作為“C”鏈接:

extern "C" void* func(void *arg)
{
  printf("Thread function called\n");
}

面臨的錯誤是:

simplepThread.cc:7: error: previous declaration of ‘void* func(void*)’ with ‘C++’ linkage
simplepThread.cc:15: error: conflicts with new declaration with ‘C’ linkage

您不能在 class 聲明中調用函數。 在 class 聲明中,您只能聲明(並且可能定義)其成員。

pthread_create(threadId, NULL, func, NULL);

不是有效的成員 function 定義。
整個 class 測試似乎是多余的。

static void* func(void *arg)
{
   printf("Thread function called\n");
}
int main()
{
  pthread_t threadId;

  pthread_create(&threadId, NULL, func, NULL);
}

應該可以正常工作。
我還修復了另一個問題 - 您試圖將未初始化的指針 ( threadId ) 傳遞給需要變量地址的 function。
更新
關於鏈接 - 你有一個默認的原型(C++ 鏈接)

void* func(void *arg);

並與C聯動定義

extern "C"
{
    void* func(void *arg)
    {
    ....
    }
}

所以他們發生沖突。 將原型更改為

extern "C"
{
  void* func(void *arg);
}

會好的

您的代碼存在許多問題。 首先,您需要為測試 class 聲明一個構造函數 function,鑒於您使用代碼的方式,我會將 pthread_create() 調用放在構造函數中。 其次,雖然 pthread_create() 將 pthread_t* 參數作為其第一個參數,這意味着該參數被用作 output 參數,並且指針應該指向新創建線程的線程 ID 所在的實際內存/變量放置。

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

static void* func(void*);

class Test
{
 public:
    pthread_t threadId;

    Test() {
       pthread_create(&threadId, NULL, func, NULL);
    }
 };

 static void* func(void *arg)
 {
   printf("Thread function called\n");
 }

 int main()
 {
  Test();
 }

通常,當您在執行多線程代碼時,您還希望確保線程在完成它們時被銷毀,或者跟蹤它們何時自行死亡。 例如,如果您創建一個“工作”線程,用於在后台異步處理工作,那么您通常希望主線程有一個互斥保護隊列,以便將工作傳遞給工作線程。 您通常還希望一些信號量或其他“安全”信號系統在程序想要退出時導致工作線程安全死亡,並使用反向信號機制,以便主線程知道工作人員何時死亡並且現在是安全的清理共享數據結構。 (即,將一項工作放入簡單地說“死亡”的作業隊列中,並讓工作人員在退出前回復“死亡”)

實現正確的多線程代碼並非易事,您必須擔心單線程代碼根本不會發生的各種問題,例如死鎖和競爭條件。 我強烈建議您閱讀並確保您完全理解這些和其他主題。

暫無
暫無

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

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