线程
- 创建线程pthread_create
/* Create a new thread, starting with execution of START-ROUTINE
getting passed ARG. Creation attributed come from ATTR. The new
handle is stored in *NEWTHREAD. */
extern int pthread_create (pthread_t *__restrict __newthread,
const pthread_attr_t *__restrict __attr,
void *(*__start_routine) (void *),
void *__restrict __arg) __THROWNL __nonnull ((1, 3));
创建线程成功后返回0,否则创建失败。通常这样使用:
pthread_create(&thread, NULL, (void *)&func, (void *)args); func是进程或者线程对应执行的函数,args是func的入参。
- 结束线程pthread_exit
/* Terminate calling thread.
The registered cleanup handlers are called via exception handling
so we cannot mark this function with __THROW.
*/
extern void pthread_exit (void *__retval) __attribute__ ((__noreturn__));
- 线程等待pthread_join
/* Make calling thread wait for termination of the thread TH. The
exit status of the thread is stored in *THREAD_RETURN, if THREAD_RETURN
is not NULL.
This function is a cancellation point and therefore not marked with
__THROW.
*/
extern int pthread_join(pthread_t __th, void **__thread_return);
pthread_create调用成功以后,新线程和老线程谁先执行是不确定的,取决与操作系统对线程的调度。如果需要等待指定的线程结束,需要使用pthread_join函数,它类似与多进程编程中的waitpid函数。执行成功时返回0,且thread_return非空。
- 举栗子:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void print_message_function(void *ptr);
int main()
{
int tmp1,tmp2;
void *retval;
pthread_t thread1, thread2;
char *message1 = "thread1:hello world!";
char *message2 = "thread2:hello world!";
int ret_thrd1, ret_thrd2;
ret_thrd1 = pthread_create(&thread1, NULL, (void*)&print_message_function, (void*)message1);
if (ret_thrd1 != 0){
printf("create thread1 fail.\n");
}else{
printf("create thread1 success.\n");
}
ret_thrd2 = pthread_create(&thread2, NULL, (void*)&print_message_function, (void*)message2);
if (ret_thrd2 !=0){
printf("create thread2 fail.\n");
}else{
printf("create thread2 success.\n");
}
tmp1 = pthread_join(thread1, &retval);
printf("thread1 return value is %d\n", (int)retval);
printf("thread1 return value is %d\n", tmp1);
if (0 != tmp1){
printf("cannot join with thread1.\n");
}
printf("thread1 end\n");
tmp2 = pthread_join(thread2, &retval);
printf("thread2 return value is %d\n", (int)retval);
printf("thread2 return value is %d\n", tmp2);
if (0 != tmp2){
printf("cannot join with thread2.\n");
}
printf("thread2 end\n");
return 0;
}
void print_message_function(void *ptr){
int i;
for (i=0;i<5;i++)
printf("%s:%d\n", (char*)ptr, i);
}
编译:gcc -o test thread_hello_world.c -lpthread
两次执行./test的结果如下。分析一下第1次执行的结果。main函数是一个父进程,父进程尝试创建2个子进程(线程)。在执行pthread_create创建线程thread1之前,进程在main函数中执行,当执行到pthread_create时,这时候已经有2个进程(在linux环境中,线程也称之为轻量级进程),分别是father,thread1。从第1次结果中可以看到,father创建thread1成功后,执行了thread1,但是thread1还没有执行结束前又回到了father进程中,father进程成功创建了thread2,这个时候已经又3个进程了:father,thread1,thread2。操作系统这个时候调度了thread2执行,但是thread2只执行了”thread2:hello world!:0"后立即切换到了thread1,把thread1中剩余没有打印完的次数执行完成。接着切换到thread2进程。等到thread1和thread2执行结束后,fahter执行到最后退出。
//第1次
$ ./test
create thread1 success.
thread1:hello world!:0
thread1:hello world!:1
thread1:hello world!:2
thread1:hello world!:3
create thread2 success.
thread2:hello world!:0
thread1:hello world!:4
thread1 return value is 23
thread1 return value is 0
thread1 end
thread2:hello world!:1
thread2:hello world!:2
thread2:hello world!:3
thread2:hello world!:4
thread2 return value is 23
thread2 return value is 0
thread2 end
//第2次
$ ./test
create thread1 success.
thread1:hello world!:0
thread2:hello world!:0
thread2:hello world!:1
thread2:hello world!:2
thread2:hello world!:3
thread2:hello world!:4
create thread2 success.
thread1:hello world!:1
thread1:hello world!:2
thread1:hello world!:3
thread1:hello world!:4
thread1 return value is 23
thread1 return value is 0
thread1 end
thread2 return value is 23
thread2 return value is 0
thread2 end
多线程的同步与互斥----锁
- 定义一个锁
//mutex
pthread_mutex_t mutex;
- 使用锁之前初始化
//在主线程中初始化锁为解锁状态
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
//在编译时初始化锁为解锁状态
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- 加锁
/* Lock a mutex. */
extern int pthread_mutex_lock (pthread_mutex_t *__mutex);
加锁成功时返回0,否则加锁失败。
- 释放锁
/* Unlock a mutex. */
extern int pthread_mutex_unlock (pthread_mutex_t *__mutex);
开锁成功时返回0,否则释放锁失败。
- 举栗子
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sharedi = 0;
void increse_num(void);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main()
{
int ret;
pthread_t thrd1, thrd2, thrd3;
ret = pthread_create(&thrd1, NULL, (void*)increse_num, NULL);
ret = pthread_create(&thrd2, NULL, (void*)increse_num, NULL);
ret = pthread_create(&thrd3, NULL, (void*)increse_num, NULL);
pthread_join(thrd1, NULL);
pthread_join(thrd2, NULL);
pthread_join(thrd3, NULL);
printf("sharedi = %d\n", sharedi);
return 0;
}
void increse_num(void)
{
long i, tmp;
for (i=0; i<100000;i++){
/* get the lock */
if (pthread_mutex_lock(&mutex) != 0){
perror("pthread_mutex_lock.");
exit(EXIT_FAILURE);
}
tmp = sharedi;
tmp++;
sharedi = tmp;
/* release the lock. */
if (pthread_mutex_unlock(&mutex) != 0){
perror("pthread_mutex_unlock.");
exit(EXIT_FAILURE);
}
}
return;
}
如果不在 increse_num函数中增加sharedi的操作前加锁,那么sharedi每次执行后的结果是随机的。加锁之后,可以保证每次结果都是确定的。
多线程的同步与互斥----信号量
信号量本质上是一个非负数的整数计数器,被用来控制对公共资源的访问。当访问公共资源的时候,调用信号量增加函数sem_post()对其进行加1,当退出访问公共资源的时候,调用函数sem_wait()来减少信号量。
- 定义一个信号量、使用前需要初始化
#include <semaphore.h>
//定义
sem_t sem;
//调用初始化函数
int sem_init(sem_t *sem, int pshared, unsigned int value);
- 信号量操作
#include <semaphore.h>
//信号量加1操作
int sem_wait(sem_t *sem);
//信号量减1操作,如果信号量已经是0,那么执行sem_post时,该操作被阻塞
int sem_post(sem_t *sem);
//不再使用该信号量时,删除它
int sem_destroy(sem_t *sem);
以上操作执行成功时返回0,否则执行失败。
- 举栗子
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define MAXSIZE 16
int stack[MAXSIZE];
int size = 0;
sem_t sem;
//creater
void provide_data(void){
int i;
for (i=0; i<MAXSIZE; i++){
stack[i] = i;
sem_post(&sem);
}
}
//consumer
void handle_data(void){
int i;
while((i = size++) < MAXSIZE){
//如果消费者的消费速度比生产者的速度快,此处会阻塞消费者;直到有值(stack[MAXSIZE])可被消费时才
//不阻塞
sem_wait(&sem);
printf("multiply: %d x %d = %d\n", stack[i], stack[i], stack[i]*stack[i]);
sleep(1);
}
}
int main(void)
{
pthread_t provider, handler;
sem_init(&sem, 0, 0);
pthread_create(&handler, NULL, (void*)handle_data, NULL);
pthread_create(&provider, NULL, (void*)provide_data, NULL);
pthread_join(provider, NULL);
pthread_join(handler, NULL);
sem_destroy(&sem);
return 0;
}
这是一个非常朴素的生产者-消费者问题,使用了信号量来保证消费者不会提前去消费生产者没有生产的值。