|
|
EDA365欢迎您登录!
您需要 登录 才可以下载或查看,没有帐号?注册
x
#include <stdio.h>
" V$ { Z1 X4 U5 S! A) r#include <stdlib.h>7 C$ k( A9 ?8 Y7 s
#include <unistd.h>4 l, u/ j; Y" x, z: c! \- v
#include <pthread.h>9 q8 _& {5 ]3 V$ b3 ]) S! N2 U
" s# B3 z9 x7 S$ `
& g, L" G# z7 t3 O7 `6 B$ d
1 \7 H# d8 g$ f9 m: l1 Y8 Q$ @3 j; Y% n4 |, \& g
int * thread(void *arg); I/ }3 A& b. U5 X0 J" y5 U
{; S2 r# s' {/ I" t( G* K" b
while(1)
7 O8 }; r3 X" f6 Z5 j) m% U{4 Y% [" i/ n! K- g
printf("It is the thread!\n");: N5 Y$ F) y1 K) M: a+ p+ Z
sleep(1);
3 g7 B5 }$ ]" L. H8 ?. k- K}
6 v: w5 u/ k, j" _; s7 w % r* s% I& [1 f6 {) R$ V
return NULL;
9 [5 s! ^! a8 f1 _}
0 y: w% s# B2 j2 M. a0 |5 Y& _1 t6 B- p; p$ ?
8 t# [" }5 `0 o1 j( Z" `) k* k
) @5 z1 n2 |; M
0 c9 F* m* j: C# e3 ?1 Q) uint main()' o6 A! R+ ~0 t- z
{
$ q |: S! j9 Epthread_t id;
1 N5 Q0 ~0 M2 O- yprintf("Main thread id is %d \n",pthread_self());# J9 j$ s: v6 E
if(!pthread_create(&id,NULL,(void *)thread,NULL))& Z$ O7 o; f4 I) U1 t
{7 W% b, s* A' |) c; ?7 h. m" V
printf("succeed!\n");
9 Q/ ^0 D3 P T2 K- ~- a, k}
3 e% b6 ~9 V4 s* |; m' _3 |" jelse6 g) f' N, O9 Z8 C3 C- [
{: @- `7 i& _6 j
printf("Fail to Create Thread");+ o& x6 h* O8 V& s- K" K. d
return -1;8 |( X" @+ h! ] x7 P7 D; L- w
}/ O# F+ J& l) ^
while(1)9 {. W @6 t1 F9 {6 M1 H
{
7 o) X n' A/ bprintf("It is the main process!\n");7 y" Z, L: M/ u" b. e, M0 D9 v+ t( c
sleep(1);
3 g# ]7 z7 d" X! q, R}; _. q3 n6 ]7 n, X2 ~
}3 i% u7 D5 L. M; T1 ]& }
* [1 ?6 I7 k4 M! w# n, J
1 b) a+ u8 _' ^% X& a% w6 jsunxk@146:~> gcc -o pthread pthread.c -lpthread
$ ?5 D5 v+ y& S- C; C8 Y8 C
4 x, O* u/ }9 a- Q! @8 ^$ W* E. r2 ~* f2 ?; {, d
sunxk@146:~> ./pthread6 R9 H* Z% K( G1 g
Main thread id is 950486784$ Y; G+ W& L% G( R- n
succeed!2 O# U8 ?1 N5 @
It is the thread!" Z& [7 L8 d5 ^/ N8 N
It is the main process!) ]2 P6 d6 F! w8 D5 k% \
It is the thread!
9 Q+ x# d: h5 ?" z% e' _- hIt is the main process!3 K1 A% K0 m2 o/ I
It is the thread!
: V3 h. M& t& D8 C( K5 ]3 N+ lIt is the main process!/ }0 n; l* r: |3 {! S
It is the thread!
; @0 Y7 Z+ |: v1 G, f: c2 \It is the main process!
- i) C1 p7 J. q' g6 O5 w% ?$ O( z7 i) t; _1 A4 F3 Q8 X0 \
$ x3 q6 |" d2 C
% _: J' z1 B8 Q8 h3 o
' f2 L- g) n6 v2 Q* W& M) |) v- O
|
|