Linux 线程总结
简述
进程与线程的区别:
相同点:多任务处理
不同点:
(1)进程有独立的内存空间(代码段、数据段、堆、栈),线程没有,进程是线程的容器
(2)相对于进程而言,线程间切换效率高,消耗内存小,多线程在同一进程下共享数据(变量),有更为简便的通信机制
常用的线程相关API函数原型(3、4、5)
#include <pthread.h>
// 创建线程、等待、退出
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
int pthread_join(pthread_t thread, void **rval_ptr);
int pthread_exit(void *rval_ptr);
// 互斥锁相关API: 创建锁、上锁、解锁、毁锁
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_lock(pthread_mutex_t *restrict mutex);
int pthread_mutex_unlock(pthread_mutex_t *restrict mutex);
int pthread_mutex_destroy(pthread_mutex_t *restrict mutex);
//条件变量相关API: 创建、触发、广播、等待、销毁
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
int pthread_cond_signal(pthread_cond_t *restrict cond);
int pthread_cond_broadcast(pthread_cond_t *restrict cond);
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
int pthread_cond_destroy(pthread_cond_t *restrict cond);
统一:成功返回0,失败返回-1
线程创建、等待、退出API使用
创建线程、等待线程
#include <stdio.h>
#include <pthread.h>
void *pthread1(void* arg)
{
//打印线程id
printf("pthread1 creat,id:%ld\n", (unsigned long)pthread_self());
//线程传参,打印data值,需强转
printf("data=%d\n", *(int *)arg);
}
// int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// int pthread_join(pthread_t thread, void **rval_ptr);
// int pthread_exit(void *rval_ptr);
int main()
{
int data = 10;
pthread_t t1;
printf("before create\n");
pthread_create(&t1, NULL, &pthread1, (void *)&data);
printf("after create\n");
pthread_join(t1, NULL);
// while(1);
return 0;
}
线程退出、传参
#include <stdio.h>
#include <pthread.h>
void *pthread1(void* arg)
{
// static int ret = 55;
static char *ret = "sunshine";
printf("pthread1 creat,id:%ld\n", (unsigned long)pthread_self());
printf("data=%d\n", *(int *)arg);
pthread_exit((void *)ret);
}
// int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// int pthread_join(pthread_t thread, void **rval_ptr);
// int pthread_exit(void *rval_ptr);
int main()
{
int data = 10;
// int *p = NULL;
char *pret = NULL;
pthread_t t1;
printf("before create\n");
pthread_create(&t1, NULL