|
|
EDA365欢迎您登录!
您需要 登录 才可以下载或查看,没有帐号?注册
x
#include <stdio.h>5 g% Q: D, P% w1 W2 \, W4 u
#include <stdlib.h>5 N% o( z8 |3 m
#include <unistd.h>5 a$ G3 F f5 N- t+ {/ m+ K
#include <pthread.h>
7 F0 P: r& n& A$ ?# w* y' o! @' b' ?+ p; C# w# n
- }& R. ?1 O8 w( C! j6 D& w2 S+ u9 F2 Y; m0 B1 H
. c# v8 A% K% ?. I) |
int * thread(void *arg)
+ T0 t& r5 F% b( f$ S{9 x" ?3 E& j3 |, m
while(1)
+ [* ^- ]; T; m% a{% f; V" L! {) M* y( w3 ^
printf("It is the thread!\n");
) r9 f+ c' l% N1 ]* Csleep(1);
( z* k/ l! y. M( L0 Z$ N- U0 C}! ]2 S3 r' T& i1 W
. x2 e& Y' T! ~. W- P- V return NULL; w. R: y8 w0 Z1 {- {5 f8 l
}% x' x6 n; [5 f
; n) ^. Q- \, y& R6 Y% @
: d# T# O. l5 H! ]
* f7 B7 }- p1 ?) M; p: O
# V& ?3 |. s( P9 q/ U4 Gint main()6 U% E3 m9 m6 Z. r1 _
{
+ h; z5 Q: R: o# ~pthread_t id;
, _& y5 O& L* ]# g9 C8 _ cprintf("Main thread id is %d \n",pthread_self());+ F! `7 G" M* V( Y H2 t @+ f
if(!pthread_create(&id,NULL,(void *)thread,NULL))
; [, R o- Q' F{+ _% U' o: D3 N! @6 W
printf("succeed!\n");! u. ]' C1 v: U$ v
}
6 E" q# _( d4 t6 g# y/ r( nelse; n$ C+ b* M4 p( x/ ?
{: {1 }+ h9 a; B
printf("Fail to Create Thread");) u/ I( S" P! C0 M6 v2 C7 J) p
return -1;
: _. e V: Z% L( Z4 O) c}
: `4 D4 o* t/ @/ P/ d! i# h1 Wwhile(1)6 C% V" ~5 u. u% Q: L9 o) i
{: ^ \2 @. l5 n" C8 I* S" Y
printf("It is the main process!\n");
9 B& ^1 W& m0 A% ?! w- osleep(1);6 h" n' i8 i& @; j
}
) T9 r. h5 h- R: M- h. O}
3 L9 @# ^ \! x6 b7 p/ _0 {9 X* U7 _5 f. b9 ]6 _% p* A- l7 L
) G, |2 D% T7 k6 X( q
sunxk@146:~> gcc -o pthread pthread.c -lpthread" L0 X' b" m- g8 {% Y( p- ~# F
' Y+ N* V6 @8 t; s
1 q8 N* i( X- ?& ~3 I; f
sunxk@146:~> ./pthread
3 b8 o/ y& \) _Main thread id is 9504867847 ~/ o) @7 b, R H
succeed!$ f4 M i. \ k" o
It is the thread!# R3 j) _8 B( G3 _, O
It is the main process!! i3 K# V0 B7 N" P2 X' r9 T( ~9 Y
It is the thread!/ ?2 ~" k* O8 e. U. P
It is the main process!2 g( |7 R- H- {. ?1 M0 J1 d$ l
It is the thread!
; r0 |5 k, r2 t$ K# [6 _It is the main process!9 Q2 L. D) ]: f
It is the thread!7 o: G6 V2 ?" u* x# O# ^9 d( C
It is the main process!' `' t* u4 c |
: ~1 J3 ]: r# X9 f5 {
% ~$ V0 w3 `* G$ B2 N
7 T/ r% C% b- h: M9 g' n
6 i; |: V+ T8 ` |
|