私はしばらくの間インターネットを検索し、さまざまな解決策を見つけましたが、すべてが実際には機能しないか、私の使用には複雑です。私は2年前までC++を使用していたので、少し錆びているかもしれません:D
私は現在、URLにデータを投稿するプログラムを書いています。データを投稿するだけです。データを投稿するためにcurlを使用しますが、メインスレッドがブロックされ、最初の投稿がまだ実行されている間に、開始する必要のある2番目の投稿があります。最終的には、約5〜6のポスト操作が同時に実行されます。
次に、curlを使用した投稿を別のスレッドにプッシュします。投稿ごとに1つのスレッド。スレッドは、何をプッシュするかを含む文字列パラメーターを取得する必要があります。
私は現在これに固執しています。Windows用のWINAPIを試しましたが、パラメータの読み取り時にクラッシュします。(私の例では、メインスレッドが終了している間(system( "pause")で待機中)、2番目のスレッドはまだ実行されています)。
WindowsとLinuxで実行されるため、マルチプラットフォームソリューションがあると便利です。
これが私の現在のコードです:
#define CURL_STATICLIB
#include <curl/curl.h>
#include <curl/easy.h>
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#if defined(WIN32)
#include <windows.h>
#else
//#include <pthread.h>
#endif
using namespace std;
void post(string post) { // Function to post it to url
CURL *curl; // curl object
CURLcode res; // CURLcode object
curl = curl_easy_init(); // init curl
if(curl) { // is curl init
curl_easy_setopt(curl, CURLOPT_URL, "http://10.8.27.101/api.aspx"); // set url
string data = "api=" + post; // concat post data strings
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); // post data
res = curl_easy_perform(curl); // execute
curl_easy_cleanup(curl); // cleanup
} else {
cerr << "Failed to create curl handle!\n";
}
}
#if defined(WIN32)
DWORD WINAPI thread(LPVOID data) { // WINAPI Thread
string pData = *((string*)data); // convert LPVOID to string [THIS FAILES]
post(pData); // post it with curl
}
#else
// Linux version
#endif
void startThread(string data) { // FUnction to start the thread
string pData = data; // some Test
#if defined(WIN32)
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread, &pData, 0, NULL); // Start a Windows thread with winapi
#else
// Linux version
#endif
}
int main(int argc, char *argv[]) {
// The post data to send
string postData = "test1234567890";
startThread(postData); // Start the thread
system("PAUSE"); // Dont close the console window
return EXIT_SUCCESS;
}
誰か提案がありますか?
助けてくれてありがとう!