榪欎釜鎵ц鐨勮繃紼嬪ぇ姒傝10縐?!!!!!
鑰屾垜浠敤鑷棆閿?浠g爜:
/*
* time :2008.4.30
* author:will cao
* Email:sei_michael@126.com
* 鎺㈢儲(chǔ)鑷棆閿佷笌淇″彿閲忕殑鍖哄埆
*/
#include<pthread.h>
#include<stdio.h>
pthread_t thread[2];
pthread_spinlock_t lock ;
#define MAX 10
int number=0,i;
void * thread1()
{
printf ("thread 1 :I began to run !");
for(i=0;i<MAX;i++)
{
printf("thread 1 :number=%d \n",number);
pthread_spin_lock(&lock);
number++;
pthread_spin_unlock(&lock);
}
printf("ok ,I am over !\n");
pthread_exit(NULL);
}
void * thread2 ()
{
printf("thread2 : I start !!!\n");
for(i=0;i<MAX;i++)
{
printf("thread2 : number = %d \n",number);
pthread_spin_lock(&lock);
number++;
pthread_spin_unlock(&lock);
}
printf("thread 2: I am over!!!");
pthread_exit(NULL);
}
void thread_create(void)
{
/*create the threads */
pthread_create(&thread[0],NULL,thread1,NULL);
printf("create the thread 1\n ");
pthread_create(&thread[1],NULL,thread2,NULL);
printf("create the thread 2 \n");
}
void thread_wait(void )
{
/*wait for the thread to be over */
pthread_join(thread[0],NULL);
printf("the thread 1 is over !\n");
pthread_join(thread[1],NULL);
printf("the thread 2 is over ! \n");
}
int main()
{
/* init the spin lock */
pthread_spin_init(&lock,0);
printf("i am the main,and I am creating the threads ");
thread_create();
printf("i am the main,and I am wait for the thread to be over!");
thread_wait();
}
鎵ц緇撴灉涓?
i am the main,and I am creating the threads thread 1 :I began to run !thread 1 :number=0
thread 1 :number=1
thread 1 :number=2
thread 1 :number=3
thread 1 :number=4
thread 1 :number=5
thread 1 :number=6
thread 1 :number=7
thread 1 :number=8
thread 1 :number=9
ok ,I am over !
create the thread 1
thread2 : I start !!!
create the thread 2
i am the main,and I am wait for the thread to be over!thread2 : number = 10
thread2 : number = 11
thread2 : number = 12
thread2 : number = 13
thread2 : number = 14
thread2 : number = 15
thread2 : number = 16
thread2 : number = 17
thread2 : number = 18
thread2 : number = 19
thread 2: I am over!!!the thread 1 is over !
the thread 2 is over !
鎵ц鏃墮棿:鎴戞病鐢ㄧ郴緇熻皟鐢?浣嗚偗瀹氭槸鐢ㄤ笉浜?.1縐掔殑...
鎬葷粨:浠庤〃闈笂鏉ョ湅,寰堟槑鏄劇殑鍖哄埆鏄綋鎴戜滑鐢ㄧ殑鏄俊鍙烽噺鐨勬椂鍊?榪欎釜鏃跺欐槸鏈夎皟搴︾殑.鍥犱負(fù)浠庤繍琛岀粨鏋滀笂鏉ョ湅,涓葷嚎紼嬪湪鍒涘緩鍏朵粬涓や釜綰跨▼鍚?鍏朵粬綰跨▼寮濮嬭繍琛?騫朵笖涓葷嚎紼嬩篃鍦ㄨ繍琛?浣嗘庝箞榪愯榪欎釜鏄棤娉曠‘瀹氱殑,榪欐槸涓涓茍鍙戠殑榪囩▼.
褰撲嬌鐢ㄨ嚜鏃嬮攣鍚?榪欎釜灝變笉涓鏍蜂簡.褰撹繍琛屽埌涓寸晫鍖虹殑鏃跺?瀹冩槸鐩存帴鐨勮繃鍘?涓嶆槸浼?xì)漶旂敓涓涓瓑寰?鎴栬呬竴涓皟搴?
涓嶇煡閬撶紪璇戝櫒鏄庝箞緙栬瘧鐨?寰堟兂鐭ラ亾緙栬瘧鍚庝簩榪涘埗浠g爜鏈変粈涔堝尯鍒?浣嗚繖涓ソ鍍忔湁鐐瑰お闅?...涓嶈繃鎴戣寰椾粠榪愯緇撴灉涓婃潵鐪嬭繖涔堝,搴旇宸笉澶氫簡.