1 #include <pthread.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 #define NUM_OF_TASKS 5
6
7 void *downloadfile(void *filename)
8 {
9 printf("I am downloading the file %s!\n", (char *)filename);
10 sleep(10);
11 long downloadtime = rand()%100;
12 printf("I finish downloading the file within %d minutes!\n", downloadtime);
13 pthread_exit((void *)downloadtime);
14 }
15
16 int main(int argc, char *argv[])
17 {
18 char files[NUM_OF_TASKS][20]={"file1.avi","file2.rmvb","file3.mp4","file4.wmv","file5
19 pthread_t threads[NUM_OF_TASKS];
20 int rc;
21 int t;
22 int downloadtime;
23
24 pthread_attr_t thread_attr;
25 pthread_attr_init(&thread_attr);
26 pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_JOINABLE);
27
28 for(t=0;t<NUM_OF_TASKS;t++){
29 printf("creating thread %d, please help me to download %s\n", t, files[t]);
30 rc = pthread_create(&threads[t], &thread_attr, downloadfile, (void *)files[t]);
31 if (rc){
32 printf("ERROR; return code from pthread_create() is %d\n", rc);
33 exit(-1);
34 }
35 }
36
37 pthread_attr_destroy(&thread_attr);
38
39 for(t=0;t<NUM_OF_TASKS;t++){
40 pthread_join(threads[t],(void**)&downloadtime);
41 printf("Thread %d downloads the file %s in %d minutes.\n",t,files[t],downloadtime)
42 }
43
44 pthread_exit(NULL);
三、线程特点(how)
线程数据