Linux 线程与互斥锁的使用
生活随笔
收集整理的這篇文章主要介紹了
Linux 线程与互斥锁的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
互斥鎖的基本函數和用于信號量的函數非常相似:
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t, *mutexattr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_destory(pthread_mutex_t *mutex);
以下是代碼實例:
#include <iostream>
#include <string>#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
using namespace std;
#define SIZE 1024
char buffer[SIZE];
void *thread_function(void *arg);
pthread_mutex_t mutex;
int main()
{
int res;
pthread_t ThreadID;
void* ThreadResult;
res = pthread_mutex_init(&mutex, NULL);
if (res != 0)
{
perror("MUTEX INIT FAILED!");
exit(EXIT_FAILURE);
}
res = pthread_create(&ThreadID, NULL, thread_function, NULL);
if (res != 0)
{
perror("Thread Create Failed!");
exit(EXIT_FAILURE);
}
printf("ThreadID:%d\n", ThreadID);
while(1)
{
pthread_mutex_lock(&mutex);
scanf("%s", buffer);
pthread_mutex_unlock(&mutex);
if (strncmp("end", buffer, 3) == 0)
{
break;
}
sleep(1);
}
res = pthread_join(ThreadID, &ThreadResult);
if (res != 0)
{
perror("Thread Join Failed");
exit(EXIT_FAILURE);
}
printf("Thread join\n");
pthread_mutex_destroy(&mutex);
return(EXIT_SUCCESS);
}
void *thread_function(void *arg)
{
sleep(1);
while(1)
{
pthread_mutex_lock(&mutex);
printf("you input %d \n", strlen(buffer));
pthread_mutex_unlock(&mutex);
if (strncmp("end", buffer, 3) == 0)
{
break;
}
sleep(1);
}
pthread_exit(NULL);
}
總結
以上是生活随笔為你收集整理的Linux 线程与互斥锁的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AIX命令参考大全,卷 4,n - r
- 下一篇: Linux 线程属性的使用