生活随笔
收集整理的這篇文章主要介紹了
操作系统原理三线程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
線程是進程中的執行流
線程比進程更節省資源.
線程間的通信比進程間的通信代價小得多.
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<pthread.h>
void* threadFunc(void* arg
){sleep(3);printf("In NEW thread\n");
}int main(){pthread_t tid
; pthread_create(&tid
,NULL,threadFunc
,NULL);printf("In main thread\n");pthread_join(tid
,NULL);return 0;
}
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<pthread.h>
#include<time.h>
#include<stdlib.h>int value
= 100;
void* hello(void* arg
){for(int i
=0; i
<3;i
++){printf("hello(%d)\n",value
++);sleep(1);}
}
void* world(void* arg
){for(int i
=0; i
<3;i
++){printf("world(%d)\n",value
++);sleep(2);}
}int main(){pthread_t tid
, tid2
;pthread_create(&tid
,NULL,hello
,NULL);pthread_create(&tid2
,NULL,world
,NULL);pthread_join(tid
,NULL);pthread_join(tid2
,NULL);printf("In main thread(%d)\n",value
);
}
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<pthread.h>
#include<time.h>
#include<stdlib.h>
#include<math.h>
#include<omp.h>void* calculate_pi(void* arg
){unsigned int seed
= time(NULL);int circle_points
= 0;int square_points
= 0;int interval
= *((int*)arg
); for(int i
= 0; i
<interval
*interval
; ++i
){double rand_x
= (double)rand_r(&seed
)/RAND_MAX
;double rand_y
= (double)rand_r(&seed
)/RAND_MAX
;if((rand_x
*rand_x
+ rand_y
*rand_y
) <= 1){circle_points
++;}square_points
++;}double pi
= (double)(4.0*circle_points
)/square_points
;printf("The estimated PI is %lf in %d times\n",pi
,interval
*interval
);pthread_exit(0);
}int main(int argc
, char const *argv
[]){clock_t start
,delta
;double time_used
;start
= clock();pthread_t calculate_pi_threads
[10];int args
[10];for(int i
=0; i
<10; i
++){args
[i
] = 1000*(i
+1);pthread_create(calculate_pi_threads
+i
,NULL,calculate_pi
,args
+i
);}for(int i
=0; i
<10; i
++){pthread_join(calculate_pi_threads
[i
],NULL);}delta
= clock() - start
;printf("The time taken in total: %lf seconds\n", (double)delta
/CLOCKS_PER_SEC
);return 0;
}
總結
以上是生活随笔為你收集整理的操作系统原理三线程的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。