我有一個函式,計算一個字串在一個char陣列中出現的次數。用findword(copy, "polar")正常呼叫這個函式,效果很好,列印出一個int,即字串 "polar "在char array "copy "中出現的次數。然而,通過pthread呼叫該函式卻給我帶來了編譯問題,我不知道為什么。這是我第一次實作多執行緒。
下面是我想呼叫的函式:
void findword(char *str,string word)
{
char *p;
向量<字串> a;
p = strtok(str, ")。
while (p != NULL)
{
a.push_back(p)。
p = strtok(NULL, " "/span>)。
}
int c = 0;
for (int i = 0; i <= a.size() ; i )
if (word == a[i])
c ;
printf("%d"/span>, c);
}
這是我試圖創建的執行緒,它應該呼叫該函式:
這是我試圖創建的執行緒。
struct findwordargs {
char *str;
字串。
};
struct findwordargs firstwordArguments。
firstwordArguments.str = copy;
firstwordArguments.word = "polar"。
pthread_t thread_id = 1;
pthread_create(&thread_id, NULL, findword, (void *)(& firstwordArguments))。
pthread_join(thread_id, NULL) 。
當我使用g 和-pthread標志進行編譯時,我得到這樣的編譯錯誤:
error: invalid conversion from 'int (*)(char*, std::string) ' {aka 'int (*)(char*, std: :__cxx11::basic_string<char>)'}改為'void* (*)(void*)' [-fpermissive]
101 | pthread_create(&thread_id, NULL, findword, (void *) (& firstwordArguments))。
所有必要的頭檔案都包括在內,謝謝你的幫助。
uj5u.com熱心網友回復:
你的findword()函式不符合pthread_create()要求的簽名:
void *(*start_routine)(void *)
嘗試這樣做:
struct findwordargs
{
char *str;
std::string word;
};
void* findword(void *param)/span>
{
findwordargs *args = static_cast<findwordargs*>(param)。
std::vector<std::string> a;
char *p = strtok(args->str, " ") 。
while (p) {
a.push_back(p)。
p = strtok(NULL, " ")。
}
int c = 0;
for (size_t i = 0; i < a.size(); i) {
if (args->word == a[i])
c ;
}
printf("%d", c) 。
/* 替代方法,使用更多的C -ish例程。
std::istringstream iss(args->str)。
std::string word;
while (iss >> word) a.push_back(word);
std::cout << std::count(a.begin(), a.end(), args-> word);
*/
return NULL。
}
...
findwordargs firstwordArguments;
firstwordArguments.str = copy;
firstwordArguments.word = "polar"。
pthread_t thread_id = 1;
pthread_create(&thread_id, NULL, findword, & firstwordArguments)。
pthread_join(thread_id, NULL) 。
這就是說,創建一個執行緒只是為了立即加入它是沒有意義的。這將阻塞呼叫的執行緒,直到生成的執行緒退出,這與直接呼叫函式的效果相同,但沒有執行緒間背景關系切換的開銷。
void findword( const std: :string &str, const std::string &word)
{
std::vector<std::string> a;
std::istringstream iss(str)。
std::string word;
while (iss >> word) a.push_back(word)。
std::cout << std::count(a.begin(),a.end(),word)。
}
...
findword(copy, "polar")。
uj5u.com熱心網友回復:
你使用pthreads而不是std::thread有什么原因嗎?如果是這樣,那就請忽略我。這是我要做的:
std:: 執行緒myThread([=](){ findword(copy, "polar"); })。
myThread.join()。
-or-
myThread.detach(); // If appropriate.。
這取決于類似于現代C 的東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/321874.html
標籤:
