1.关于编译时出现 对‘pthread_create’未定义的引用 之类的错误的解决:由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数:
gcc -o pthread pthread.c -lpthread
2.pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果进程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
int pthread_join(pthread_t thread, void **retval);
thread: 线程标识符,即线程ID,标识唯一线程。
retval: 用户定义的指针,用来存储被等待线程的返回值。
子线程还没有执行完毕,main函数已经退出,那么子线程也就退出了!
这个特性和父进程子进程相同。
所以要使用 pthread_join(pthread_t thread, void **retval);函数来等待子线程执行完毕,接下来才能进行主线程里的程序代码。
3.pthread_create函数:
声明:
int pthread_create(pthread_t *thread,
const pthread_attr_t *restrict_attr,
void*(*start_rtn)(void*),
void *restrict arg);
第一个参数 *thread 为指向线程标识符的指针。
第二个参数 *restrict_attr 用来设置线程属性,上面也可以用NULL,表示使用默认的属性。
第三个参数 是线程运行函数的起始地址。
最后一个参数是子线程函数运行时带入的参数,NULL表示无参数。
4.pthread_mutex_trylock()调用在参数mutex指定的mutex对象当前被锁住的时候立即返回,除此之外,pthread_mutex_trylock()跟pthread_mutex_lock()功能完全一样。
5.函数 pthread_mutex_init(&mutex,NULL)用来生成一个互斥锁,第二个参数是定义了互斥锁(mutex)的属性,NULL为默认属性。如果需要声明特定属性的互斥锁,须调用函数 pthread_mutexattr_init。