初始化互斥锁

int pthread\_mutex\_init(pthread\_mutex\_t *mutex, const pthread\_mutexattr\_t *attr);

上锁

int pthread\_mutex\_lock(pthread\_mutex\_t *mutex);


解锁

int pthread\_mutex\_unlock(pthread\_mutex\_t * mutex);

销毁互斥锁

int pthread\_mutex\_destroy(pthread\_mutex\_t *mutex);

**\#include <stdio.h>
\#include <stdlib.h>
\#include <pthread.h>
\#include <unistd.h>

pthread\_mutex\_t mutex;
// print
void printer(char *str)
{
pthread\_mutex\_lock(&mutex);
while(*str!='\0')
{
putchar(*str);
fflush(stdout);
str++;
sleep(1);
}
printf("\n");
pthread\_mutex\_unlock(&mutex);
}

// thread one
void *thread\_fun\_1(void *arg)
{
char *str = "hello";
printer(str);
}

// thread two
void *thread\_fun\_2(void *arg)
{
char *str = "world";
printer(str);
}

int main(void)
{
pthread\_t tid1, tid2;
int err1, err2;
pthread\_mutex\_init(&mutex, NULL);
// creat two thread
err1 = pthread\_create(&tid1, NULL, thread\_fun\_1, NULL);
err2 = pthread\_create(&tid2, NULL, thread\_fun\_2, NULL);
// wait thread end
pthread\_join(tid1, NULL);
pthread\_join(tid2, NULL);
pthread\_mutex\_destroy(&mutex);
return 0;
}**

标签: linux, int, pthread, NULL, str, thread, mutex, 互斥, 解锁

相关文章推荐

添加新评论,含*的栏目为必填