]> git.ipfire.org Git - thirdparty/curl.git/commitdiff
examples/multithread: fix race condition
authorStefan Eissing <stefan@eissing.org>
Fri, 14 Nov 2025 11:51:31 +0000 (12:51 +0100)
committerDaniel Stenberg <daniel@haxx.se>
Fri, 14 Nov 2025 14:11:53 +0000 (15:11 +0100)
Reported-by: Nick Korepanov
Fixes #19524
Closes #19526

docs/examples/multithread.c

index 36836ef4753374232efc040cd8deda0815408e01..3ecca259082053039936427e0925356935fc8e6e 100644 (file)
@@ -50,14 +50,19 @@ static const char * const urls[NUMT]= {
   "www.example"
 };
 
-static void *pull_one_url(void *pindex)
+struct targ {
+  const char *url;
+};
+
+
+static void *pull_one_url(void *p)
 {
   CURL *curl;
+  struct targ *targ = p;
 
   curl = curl_easy_init();
   if(curl) {
-    int i = *(int *)pindex;
-    curl_easy_setopt(curl, CURLOPT_URL, urls[i]);
+    curl_easy_setopt(curl, CURLOPT_URL, targ->url);
     (void)curl_easy_perform(curl); /* ignores error */
     curl_easy_cleanup(curl);
   }
@@ -76,6 +81,7 @@ int main(void)
 {
   CURLcode res;
   pthread_t tid[NUMT];
+  struct targ targs[NUMT];
   int i;
 
   /* Must initialize libcurl before any threads are started */
@@ -84,10 +90,12 @@ int main(void)
     return (int)res;
 
   for(i = 0; i < NUMT; i++) {
-    int error = pthread_create(&tid[i],
-                               NULL, /* default attributes please */
-                               pull_one_url,
-                               (void *)&i);
+    int error;
+    targs[i].url = urls[i];
+    error = pthread_create(&tid[i],
+                           NULL, /* default attributes please */
+                           pull_one_url,
+                           (void *)&targs[i]);
     if(error)
       fprintf(stderr, "Couldn't run thread number %d, errno %d\n", i, error);
     else