[技術] Linux多執行緒程式

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);
}

If you enjoyed this post Subscribe to our feed

No Comment

張貼留言