一、线程创建
#include <stdio.h>
#include <unistd.h> //posix标准的unix标准接口
#include <pthread.h>
pthread_t tid1; //线程id
pthread_t tid2;
void *fun1() //线程函数
{
pid_t pid = getpid(); //获取进程id
pthread_t tid = pthread_self(); //获取线程id
printf("fun1, pid = %d, tid = %d\n", pid, tid); //打印函数名和线程id
return;
}
void *fun2() //线程函数
{
pthread_t tid = pthread_self(); //获取线程id
printf("fun2, tid = %d\n", tid); //打印函数名和线程id
return;
}
int main()
{
int n = 10;
pthread_create(&tid1, 0, fun1, 0); //线程创建
pthread_create(&tid2, 0, fun2, 0);
return 0;
}
// gcc test.c -o test -lpthread
// ./test
二、线程栈大小、线程数量
1、查看 linux 系统默认设置
(1)用来查看系统当前用户进程的各种设置。
ulimit -a
(2)max user processer —— 设置每个用户的最大进程数量
ulimit -u 7864
ulimit -u 10240
(3)open file —— 设置每个进程可以打开的最大文件数目,内核可以同时打开的文件描述符的最大值
ulimit -n 4096
(4)stack size —— 临时改变栈空间大小
ulimit -s 8192 #即8M。
32位linux下的进程用户空间是3G,即3072M, 3072 M/8M=384个。
三、线程同步与通信
1、互斥量(mutex)
(1)创建、初始化
#include <pthread.h>
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, 0);
(2)加锁、解锁
pthread_mutex_lock(&mutex); //申请锁
pthread_mutex_trylock(&mutex); //尝试申请锁,非阻塞轮询
pthread_mutex_unlock(&mutex); //释放锁
2、条件变量(condition)
(1)创建、初始化
#include <pthread.h>
pthread_cond_t cond;
pthread_cond_init(&cond, 0);
(2)等待、通知
pthread_cond_wait(&cond, &mutex); //等待
pthread_cond_timewait(&cond, &mutex); //超时等待
pthread_cond_signal(&cond); //通知一个等待的线程
pthread_cond_broadcast(&cond); //通知所有等待的线程
3、信号量(semaphore)
(1)创建、初始化
#include <semaphore.h> //自己加头文件
sem_t sem;
sem_init(&sem, 0, 0); //信号量,局部,初始值
(2)等待、释放
sem_wait(&sem); //等待
sem_post(&sem); //释放