Written on 8:20 下午 by Yu Lai
From: http://blog.csdn.net/lcrystal623/archive/2007/03/05/1521170.aspx
pthread_cleanup_push和pthread_cleanup_pop是一對的。push中第一個參數是函數,第二個參數是函數的參數,pop為0表示彈出時不執行,否則再執行到pop時會執行push中指定的函數。在他們之間的程序段如果退出則執行push中指定的函數。
代碼如下:
#include <stdio.h>
#include <pthread.h>
void display()
{
printf("Hello lcrystal!\n");
}
void fun()
{
pthread_cleanup_push((void *)display,NULL);
pthread_exit(0);
pthread_cleanup_pop(0);
}
int main()
{
pthread_t id;
pthread_create(&id,NULL,(void *)fun,NULL);
pthread_join(id,NULL);
return 0;
}
Posted in
技術,
Linux,
Thread
|
Written on 7:20 下午 by Yu Lai
整個程式並沒有體現出對共享資源鎖的保護使用,只是個簡單的例子,原理完全正確,但由於簡單,CPU運行一定會順利的執行,因此不加鎖結果也相同。主要目的是演示如何建立執行緒,如何建立mutex實現共享鎖。代碼如下:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
int resource = 0;
pthread_mutex_t mutex;
void handle()
{
int i;
for(i = 0; i < 10; i++)
{
pthread_mutex_lock(&mutex);
resource++;
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
pthread_t id;
int i ;
int ret;
ret = pthread_mutex_init(&mutex,NULL);
if(ret != 0)
{
printf("創建共享鎖失敗!\n");
exit(1);
}
ret = pthread_create(&id,NULL,(void *)handle,NULL);
if(ret != 0)
{
printf("創建線程出錯!\n");
exit(1);
}
for(i = 0; i < 10; i++)
{
pthread_mutex_lock(&mutex);
printf("%d\n",resource);
pthread_mutex_unlock(&mutex);
sleep(2);
}
pthread_join(id,NULL);
pthread_mutex_destroy(&mutex);
return (0);
}
Posted in
技術,
Linux,
Thread
|