EDA365电子论坛网

标题: Linux线程创建 [打印本页]

作者: mytomorrow    时间: 2019-8-9 09:00
标题: Linux线程创建
#include <stdio.h>
% a: c% `8 c  @3 D  A: S6 Q#include <stdlib.h>
4 W4 G- C0 L2 C3 J7 o6 ~( F8 \#include <unistd.h>/ i  V7 n4 s) k8 G6 M* P5 l# j
#include <pthread.h>- X, y/ p2 u+ f8 H2 s$ \

% A8 S. S5 n6 T- i* q

3 }0 X0 d) k- Q: A, J5 d  G* o; v# h/ G& X' {' ]$ z
4 u- w, K9 {/ w
int * thread(void *arg)
  @$ M1 s6 l  `{
& G! {6 a! ?; c; s4 X# xwhile(1); Q& _0 w/ i) V
{! S( [) N8 b* o3 m; g
printf("It is the thread!\n");
. ]  z% M) C0 Y. {sleep(1);" H8 p6 G+ U6 m; _& d! E0 p- e
}
9 J8 Y! f: L& z% G0 s2 V" h   
' ^( u' h9 L; z' H    return NULL;! R( v! z2 Q1 H+ d" c3 h
}" o) `! m0 U1 A1 m% ^2 Z

1 I9 v+ K4 W. q; ~- L1 p

! O1 [4 @) ]! j* j" L# i7 }# T  a+ {! j& \" z% h
$ Y& ~9 V  J5 F& ^; ?
int main()
. p' }5 T4 J4 A. h( [{2 d$ h( n3 s1 l
pthread_t id;) \( u( [* G% T$ c' @* C) Z+ e# H
printf("Main thread id is %d \n",pthread_self());
2 }. W0 p$ `& |if(!pthread_create(&id,NULL,(void *)thread,NULL))
4 Y& J; e# f) X" Z{7 g% a( s$ _* {! N/ |1 l( ]
printf("succeed!\n");
. Y2 t1 N/ O" P- W* d}$ ?- K$ b- W  X
else2 K$ l7 k, @- v% l  r$ N
{
5 J' Q8 t6 O; r' Qprintf("Fail to Create Thread");
; Z8 m& E* L, D( g6 N7 sreturn -1;
) r4 }+ c4 ]& Z. m3 d+ ^! e' `}
. T2 L7 R0 ^, Xwhile(1)
) Z* V( P' i- @0 v5 Y8 H( G& ?, h{- t. x2 l) P" V7 p. g6 Y! a. x
printf("It is the main process!\n");; |! D& f, T# `( [: W
sleep(1);
6 j6 t& }: n$ z; o2 S}; A" `, [5 s  i- C) j
}) O7 N0 Q3 k5 ~5 _3 b

, n. a3 z8 n4 f0 @( u5 u
2 }$ r, C% N, D  n. Y2 T* i
sunxk@146:~> gcc -o pthread pthread.c -lpthread2 b2 M% }# Y' n; L% s; K% A# t
+ \$ Q6 J6 X' w% e' f% O
4 i, M# h; z1 c9 [) c; D
sunxk@146:~> ./pthread
) h% Q' k- I* n2 N2 oMain thread id is 950486784
3 N. |, w3 h5 E4 t8 Lsucceed!% F! I! g8 f. ]! o' M" L, r
It is the thread!, P* Y2 t9 E* M
It is the main process!
* i. Y$ L8 p9 I( `It is the thread!
' m. o/ m( I- v4 x- [( }+ bIt is the main process!9 M# R* T$ K, h; i8 S5 |- P
It is the thread!$ A: f+ o3 T' D/ i8 ~, R& U+ q
It is the main process!
  e8 `$ M, q( r  i" |+ @% fIt is the thread!0 C; k% |% N1 G. H3 N
It is the main process!* f4 \" K6 L+ b4 p: n
( Q$ Y9 v4 Y5 s+ x8 H! E
0 P. l! g) p1 q& G
3 i" p: ]1 j( u( w! }9 O7 t

+ `0 H( ^5 D# J: A( ?/ w
作者: fanichicl    时间: 2019-8-9 17:55
研究研究




欢迎光临 EDA365电子论坛网 (https://bbs.eda365.com/) Powered by Discuz! X3.2