Skip to content

Commit ef9d61a

Browse files
committed
URL loader mutex on threads response
1 parent e503b58 commit ef9d61a

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

libs/openFrameworks/utils/ofURLFileLoader.cpp

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ ofEvent<ofHttpResponse> & ofURLResponseEvent() {
3434
}
3535

3636
#if !defined(TARGET_IMPLEMENTS_URL_LOADER)
37+
std::mutex responseMutex;
3738
class ofURLFileLoaderImpl : public ofThread, public ofBaseURLFileLoader {
3839
public:
3940
ofURLFileLoaderImpl();
@@ -261,37 +262,41 @@ void ofURLFileLoaderImpl::threadedFunction() {
261262

262263
namespace {
263264
size_t saveToFile_cb(void * buffer, size_t size, size_t nmemb, void * userdata) {
265+
std::lock_guard<std::mutex> lock(responseMutex);
264266
auto saveTo = (ofFile *)userdata;
265267
saveTo->write((const char *)buffer, size * nmemb);
266268
return size * nmemb;
267269
}
268270

269271
size_t saveToMemory_cb(void * buffer, size_t size, size_t nmemb, void * userdata) {
272+
std::lock_guard<std::mutex> lock(responseMutex);
270273
auto response = (ofHttpResponse *)userdata;
271274
response->data.append((const char *)buffer, size * nmemb);
272275
return size * nmemb;
273276
}
274277

275278
size_t readBody_cb(void * ptr, size_t size, size_t nmemb, void * userdata) {
279+
std::lock_guard<std::mutex> lock(responseMutex);
276280
auto body = (std::string *)userdata;
277-
278281
if (size * nmemb < 1) {
279282
return 0;
280283
}
281-
282284
if (!body->empty()) {
283285
auto sent = std::min(size * nmemb, body->size());
284286
memcpy(ptr, body->c_str(), sent);
285287
*body = body->substr(sent);
286288
return sent;
287289
}
288-
289290
return 0; /* no more data left to deliver */
290291
}
291292
}
292293

293294
ofHttpResponse ofURLFileLoaderImpl::handleRequest(const ofHttpRequest & request) {
294295
std::unique_ptr<CURL, void (*)(CURL *)> curl = std::unique_ptr<CURL, void (*)(CURL *)>(curl_easy_init(), curl_easy_cleanup);
296+
if (!curl) {
297+
ofLogError("ofURLFileLoader") << "curl_easy_init() failed!";
298+
return ofHttpResponse(request, -1, "CURL initialization failed");
299+
}
295300
curl_slist * headers = nullptr;
296301
curl_version_info_data *version = curl_version_info( CURLVERSION_NOW );
297302
if(request.verbose) {
@@ -427,7 +432,12 @@ void ofURLFileLoaderImpl::update(ofEventArgs & args) {
427432
ofHttpResponse response;
428433
while (responses.tryReceive(response)) {
429434
try {
430-
response.request.done(response);
435+
std::lock_guard<std::mutex> lock(responseMutex);
436+
if (response.request.done) {
437+
response.request.done(response);
438+
} else {
439+
ofLogWarning("ofURLFileLoader") << "No callback set for request: " << response.request.url;
440+
}
431441
} catch (...) {
432442
}
433443

0 commit comments

Comments
 (0)