我正在使用_beginthead()來啓動我的線程。我需要傳遞3個參數給線程:一個字符串和兩個整數。 這是我所擁有的,這決不是整個程序,我已經採取了一些與問題無關的事情(忽略主要的錯誤,因爲在我的實際程序中主要不是主要的它只是一個常規功能):將int和字符串參數傳遞給線程C++
typedef struct ST
{
char *ip;
int port;
int dur;
}thestruct;
void main(char **arg_p, int arg_count)
{
char *ip;
int port, duration;
ip = (char *)malloc(sizeof(char));
ip = arg_p[0];
port = atoi(arg_p[1]);
duration = atoi(arg_p[2]);
thestruct *st;
st = (thestruct *)malloc(sizeof(thestruct));
st->dur = duration;
st->ip = (char *)malloc(sizeof(char));
st->ip = ip;
printf("ip: %s\n", st->ip);
st->port = port;
_beginthread((void(*)(void*))connect, 0, (void*)st);
}
void connect(thestruct *s)
{
Sleep(100);
char *ip = static_cast<char*>(s->ip);
int port = s->port;
int dur = s->dur;
printf("ip: %s\nport: %i\ndur: %i", ip, port, dur);
_endthread();
}
一切都很好,除了字符串,IP,沒有得到正確傳遞給線程。第一個printf調用完全打印出ip,然後在線程內打印「ip:」,之後它爲空。然後它進入一個新的行並完美地打印出端口和持續時間。
我一直在研究這個問題的主題一段時間沒有用,因爲大多數人只需要傳遞一個字符串或類似的東西。所以我可以從Google上找到的只有一個字符串,當然這很有用。
我通過例如「127.0.0.1 1234 25」。另外,我的結構似乎沒有任何問題,因爲就像我所說的那樣,這兩個整數完美地工作,並且我沒有在字符串上發現任何錯誤,只是沒有被傳遞。
所以無論如何,如果任何人都可以在這個話題上閃耀一些光芒,那會很棒。
僅供參考:在C++中不需要'typedef struct' /'typedef class'。 –
你作爲程序參數傳遞了什麼? –
我的想法是,當它應該是一個整數時,你使用'char ** arg_p'作爲第一個參數。 –