multithread.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2017, 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.haxx.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. ***************************************************************************/
  22. /* <DESC>
  23. * A multi-threaded example that uses pthreads to fetch several files at once
  24. * </DESC>
  25. */
  26. #include <stdio.h>
  27. #include <pthread.h>
  28. #include <curl/curl.h>
  29. #define NUMT 4
  30. /*
  31. List of URLs to fetch.
  32. If you intend to use a SSL-based protocol here you might need to setup TLS
  33. library mutex callbacks as described here:
  34. https://curl.haxx.se/libcurl/c/threadsafe.html
  35. */
  36. const char * const urls[NUMT]= {
  37. "https://curl.haxx.se/",
  38. "ftp://cool.haxx.se/",
  39. "http://www.contactor.se/",
  40. "www.haxx.se"
  41. };
  42. static void *pull_one_url(void *url)
  43. {
  44. CURL *curl;
  45. curl = curl_easy_init();
  46. curl_easy_setopt(curl, CURLOPT_URL, url);
  47. curl_easy_perform(curl); /* ignores error */
  48. curl_easy_cleanup(curl);
  49. return NULL;
  50. }
  51. /*
  52. int pthread_create(pthread_t *new_thread_ID,
  53. const pthread_attr_t *attr,
  54. void * (*start_func)(void *), void *arg);
  55. */
  56. int main(int argc, char **argv)
  57. {
  58. pthread_t tid[NUMT];
  59. int i;
  60. int error;
  61. /* Must initialize libcurl before any threads are started */
  62. curl_global_init(CURL_GLOBAL_ALL);
  63. for(i=0; i< NUMT; i++) {
  64. error = pthread_create(&tid[i],
  65. NULL, /* default attributes please */
  66. pull_one_url,
  67. (void *)urls[i]);
  68. if(0 != error)
  69. fprintf(stderr, "Couldn't run thread number %d, errno %d\n", i, error);
  70. else
  71. fprintf(stderr, "Thread %d, gets %s\n", i, urls[i]);
  72. }
  73. /* now wait for all threads to terminate */
  74. for(i=0; i< NUMT; i++) {
  75. error = pthread_join(tid[i], NULL);
  76. fprintf(stderr, "Thread %d terminated\n", i);
  77. }
  78. return 0;
  79. }