[英]POSIX thread, passing multiple arguments to function with a struct
因此,我花了最后幾個小時嘗試使用google找出我的代碼出了什么問題,但我無法弄清楚。
我是一名學生,剛開始學習線程等知識,所以這對我來說是全新的,我也不是很有經驗。
谷歌(和這里)的答案通常是代碼中一個特定問題的答案,我不知道該如何真正地工作。
這是我的代碼的非常簡化的版本:
#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
struct Data{
string a;
string b;
};
void* thread_func( void *param ){
struct Data *input = (struct Data*)param;
string data1 = input->a;
string data2 = input->b;
cout << "You said: " << data1 << " " << data2 << endl;
return NULL;
}
int main( int argc, char *argv[] )
{
pthread_t child;
string arg, arg2;
struct Data *input;
cout << "Input 1: " << endl;
cin >> arg;
cout << "Input 2: " << endl;
cin >> arg2;
input->a = arg;
input->b = arg2;
pthread_create( &child, NULL, thread_func, (void *)&input);
pthread_join( child, NULL );
cout << "Synced" << endl;
return 0;
}
所以我有一個結構數據,我想用來將多個參數傳遞給函數thread_func。
我的代碼實際上已經編譯(至少在Linux上),但是當我輸入兩個值時,都會遇到細分錯誤。
我顯然做錯了,我的猜測可能是18號線,但是我沒有足夠的經驗來獨自解決這個問題,因此我想向大家尋求幫助。
我將這個結構的多個參數傳遞給函數時,我在做什么呢?
我的實際任務要比這復雜一些,但是我盡力使它盡可能清晰。
在您的main()
函數中,這是:
struct Data *input;
創建指向struct Data
的指針,但不創建實際的struct Data
對象本身。 您需要在這里使用:
struct Data input;
接着:
input.a = arg;
input.b = arg2;
其余應正常工作。
這行:
struct Data *input;
將輸入定義為指針,但是在以后使用它在此處存儲字符串之前,它永遠不會分配對象:
input->a = arg;
input->b = arg2;
根據您對pthread_create
的調用,我懷疑您根本不希望input
成為指針。 刪除*
,然后將分配更改為:
input.a = arg;
input.b = arg2;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.