multithread.c 2.6 KB

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