2
0

multithread.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. /* <DESC>
  25. * A multi-threaded program using pthreads to fetch several files at once
  26. * </DESC>
  27. */
  28. #include <stdio.h>
  29. #include <pthread.h>
  30. #include <curl/curl.h>
  31. #define NUMT 4
  32. /*
  33. List of URLs to fetch.
  34. If you intend to use a SSL-based protocol here you might need to setup TLS
  35. library mutex callbacks as described here:
  36. https://curl.se/libcurl/c/threadsafe.html
  37. */
  38. const char * const urls[NUMT]= {
  39. "https://curl.se/",
  40. "ftp://example.com/",
  41. "https://example.net/",
  42. "www.example"
  43. };
  44. static void *pull_one_url(void *url)
  45. {
  46. CURL *curl;
  47. curl = curl_easy_init();
  48. curl_easy_setopt(curl, CURLOPT_URL, url);
  49. curl_easy_perform(curl); /* ignores error */
  50. curl_easy_cleanup(curl);
  51. return NULL;
  52. }
  53. /*
  54. int pthread_create(pthread_t *new_thread_ID,
  55. const pthread_attr_t *attr,
  56. void * (*start_func)(void *), void *arg);
  57. */
  58. int main(int argc, char **argv)
  59. {
  60. pthread_t tid[NUMT];
  61. int i;
  62. /* Must initialize libcurl before any threads are started */
  63. curl_global_init(CURL_GLOBAL_ALL);
  64. for(i = 0; i< NUMT; i++) {
  65. int error = pthread_create(&tid[i],
  66. NULL, /* default attributes please */
  67. pull_one_url,
  68. (void *)urls[i]);
  69. if(0 != error)
  70. fprintf(stderr, "Couldn't run thread number %d, errno %d\n", i, error);
  71. else
  72. fprintf(stderr, "Thread %d, gets %s\n", i, urls[i]);
  73. }
  74. /* now wait for all threads to terminate */
  75. for(i = 0; i< NUMT; i++) {
  76. pthread_join(tid[i], NULL);
  77. fprintf(stderr, "Thread %d terminated\n", i);
  78. }
  79. curl_global_cleanup();
  80. return 0;
  81. }