multithread.c 1.9 KB

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