socket多线程通信

mac2026-03-31  4

进程与线程的区别:

进程:在操作系统构成单独执行流的单位。 线程:在进程构成单独执行流的单位

线程的创建和执行流程 #include <pthread.h>

int pthread_create(pthread_t * restrict thread,const pthread_attr_t * restrict attr, void * (* start_routine)(void *),void * restrict arg); 成功时返回0,失败时返回其他值 参数:thread 保存新创建线程ID的变量地址值。线程与进程相同,也需要用于区分不同线程的ID。 attr 用于传递线程属性的参数,传递NULL时,创建默认的线程。 start_routine 相当于线程main函数的、在单独执行流中执行的函数地址值(函数指针)。 argue 通过第三个参数传递调用函数时包含传递参数信息的变量地址值 控制线程的执行流 #include<pthread.h> int pthread_join(pthread_t thread,void ** status); 成功时返回0,失败时返回其他值。 参数:thread 该参数ID的线程终止后才会从该函数返回。 statues 保存线程的main函数返回值的指针变量地址值。

线程同步 互斥量的创建和销毁函数 #include <pthread.h> int pthread_mutex_init(pthread_mutex_t * mutex,const pthread_mutexattr_t * attr); int pthread_mutex_destroy(pthread_mutex_t * mutex); 成功时返回0,失败时返回其他值 参数:mutex 创建互斥量时传递保存互斥量的变量地址值,销毁时传递需要销毁的互斥量地址值 attr 传递即将创建的互斥量属性,没有特别需要指定的属性时传递NULL。 锁住或释放临界区的函数 #include <pthread.h> int pthread_mutex_lock(pthread_mutex_t * mutex); int pthread_mutex_unlock(pthread_mutex_t * mutex); 成功时返回0,失败时返回其他值。 临界区的大小会影响程序的运行时间。 信号量 #include<semaphore.h> int sem_init(sem_t * sem,int pshared,unsigned int value); int sem_destroy(sem_t * sem); 成功时返回0,失败时返回其他值。 参数:sem 创建信号量时传递保存信号量的变量地址值,销毁时传递需要销毁的信号量变量地址值。 pshared 传递其他值时,创建可由多个进程共享的信号量;传递0时,创建只允许1个进程内部使用的信号量。我们需要完成同一进程内的线程同步,故传递0. value 制定新创建的信号量初始值。 相当于互斥量的lock,unlock函数 #include<semaphore.h> int sem_post(sem_t * sem); int sem_wait(sem_t * sem); 成功时返回0,失败时返回其他值。 参数: sem 传递保存信号量读取值的变量地址值,传递给sem_post时信号量增1,传递给 sem_wait时信号量减1. 线程的销毁的方法 #include<pthread.h> int pthread_detach(pthread_t thread); 成功时返回,失败时返回其他值。 参数: thread 终止的同时需要销毁的线程ID。 临界区 定义:函数内同时运行多个线程时引起问题的多条语句构成的代码块。

windows下的 再次进入non-signaled状态的内核对象成为“auto-reset模式”的内核对象,而不会自动跳转到non-signaled状态的内核对象称为“manual-reset模式”的内核对象。

最新回复(0)