Linux C 线程和竞争
Linux系统下的多线程遵循POSIX线程接口, 称为pthread.
使用POSIX线程需要在编译时加上-lpthread
选项
线程
- pthread_create 创建线程
- pthread_join 等待指定线程结束
- pthread_exit 退出线程
创建线程
c code
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <pthread.h>
void if_error(int stat_code, char* err_msg)
{
if (stat_code < 0) {
perror(err_msg);
exit(errno);
}
}
void* thread_proc(void *arg)
{
sleep(2);
printf("thread arg is %d .\n", *((int *)arg));
/* thread exit */
pthread_exit(NULL);
return NULL;
}
int main(int argc, char **argv)
{
pthread_t thread;
int ret, arg = 5;
/* create thread and run it */
ret = pthread_create(&thread, NULL, thread_proc, (void *)&arg);
if_error(ret, "pthread_create");
/* when thread finish */
ret = pthread_join(thread, NULL);
if_error(ret, "pthread_join");
printf("back to main thread .\n");
return 0;
}
互斥与同步
多线程中为了解决资源竞争的解决方法.
自旋锁和互斥锁
自旋锁和互斥锁的功能和使用方法都相同
使得锁到解锁之间的一系列操作成为原子操作
自选锁使用的是忙等待查询, 而互斥锁使用的是睡眠唤醒机制.
所以自旋锁效率高但一直占用CPU资源, 并容易造成死锁.
功能 | 互斥锁 | 自旋锁 |
---|---|---|
锁类型定义 | pthread_mutex_t | pthread_spin_t |
锁初始化函数 |