多线程传参,分为两种方式。一种是设置 ==全局变量==;另一种是通过int pthread_create((pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
函数的最后一项参数传参,通过pthread_create 参数传参要注意,其参数类型为(void *)。
设置全局变量时,应该注意加上同步机制,例如如p v操作或者锁机制。避免多线程访问同一资源时发生竞争。如果线程个数可以确定,线程间是同步进行的,则线程间的私有资源(线程间使用的buffer,变量)不需要加锁,这种情况一般是设置全局标志来使线程同步。
函数传参时,避免主程序因为等待线程而阻塞,使用
pthread_detach(pid)
函数使线程函数自运行。则该线程运行结束后会自动释放所有资源。使用函数传参时,注意以下几个易错点:
1. 传递的参数类型是个(void型)指针。
2. 参数传递中,不能使用局部变量int a
, 以&a
的方式传参。可采用
int a = 5;//局部变量
pthread_create(pid, NULL, thread_func, (void *)a);
........
void *thread_func(void *argc)
{
......
b = (int )argc;//实现局部变量的对线程函数的传参
......
}
函数传参例子
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>