基础线程学习
关于头文件pthread.h内主要函数及参数学习:
1.pthread_create函数
函数声明:
int pthread_create(pthread_t *restrict_tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict_arg);
参数说明:
第一个参数restrict_tidp是指线程成功创建时的线程ID
第二个参数是指创建线程的属性
第三个参数是指线程调用的运行函数
第四个参数是指调用的函数传递的参数
若成功则返回0,否则返回出错编号。返回成功时,由tidp指向的内存单元被设置为新创建线程的线程ID。attr参数用于指定各种不同的线程属性。新创建的线程从start_rtn函数的地址开始运行,该函数只有一个万能指针参数arg,如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg的参数传入。
2.pthread_mutex_init锁的调用
函数声明:
int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);
pthread_mutex_init()函数是以动态方式创建互斥锁的,参数attr指定了新建互斥锁的属性。如果参数attr为空,则使用默认的互斥锁属性,默认属性为快速互斥锁 。pthread_mutexattr_init()函数成功完成之后会返回零,其他任何返回值都表示出现了错误。
3.pthread_join函数
函数声明:
int pthread_join(pthread_t thread, void **retval);
参数 :
thread: 线程标识符,即线程ID,标识唯一线程。[线程创建时候生成,即pthread_create(pthread_t *register_tidp,…)中的registered_tidp]
retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 :
0代表成功。 失败,返回的则是错误号
pthread_join():使一个线程等待另一个线程结束。
代码中如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行。
1,2,3综合举例使用:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *function(void *arg);
pthread_mutex_t mutex;
int counter = 0;
int main(int argc, char *argv[])
{
int rc1,rc2;
char *str1="wenhaoll";
char *str2="linglong";
pthread_t thread1,thread2;
pthread_mutex_init(&mutex,NULL);
if((rc1 = pthread_create(&thread1,NULL,function,str1)))
{
fprintf(stdout,"thread 1 create failed: %d\n",rc1);
}
if(rc2=pthread_create(&thread2,NULL,function,str2))
{
fprintf(stdout,"thread 2 create failed: %d\n",rc2);
}
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
void *function(void *arg)
{
char *m;
m = (char *)arg;
pthread_mutex_lock(&mutex);
while(*m != '\0')
{
printf("%c",*m);
fflush(stdout);
m++;
sleep(1);
}
printf("\n");
pthread_mutex_unlock(&mutex);
}
增加:关于线程调用函数有多个参数时的情况
把要传递的参数结合成结构体形式
如
typedef struct {
int year;
char name[20];
}people;
void *fun1(void *arg){
people *p;
p=(people*)arg;
printf("thread1:name:%s year:%d\n",p->name,p->year);
void *fun2(void *arg){
people *p;
p=(people*)arg;
printf("thread2:name:%s year:%d\n",p->name,p->year);
}
int main(){
pthread_t thread1,thread2;
people P1,P2;
P1.year=20;
strcpy(P1.name,"susan");
P2.year=25;
strcpy(P1.name,"li");
pthread_create(&thread1,NULL,fun1,(void*)&P1);
pthread_create(&thread2,NULL,fun2,(void*)&P2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
问题:在线程池代码中看见一行,如下
pool->threads=malloc(sizeof(pthread_t)*thread_num)
不是说malloc是void*类型吗?而threads在结构体中的声明是thread_t *threads,是unsigned long int 型,不太理解为什么malloc动态分配的值不经过强制类型转换就能赋值给pool->threads还不报错呢?