查看代码
线程的创建与终止
创建
void *thread_function(void *index)
e = pthread_create(
pthread_t *thread_id,
const pthread_attr_t *attr,
thread_function,
void *index
);
thread_id为所创建线程的id
attr为线程的属性
thread_function给所创建的线程附加内容
index给thread_function函数提供所需要的参数
终止
pthread_exit(void *retval)
线程连接
int pthread_join(
pthread_t tid, //需要等待的线程,指定的线程必须位于当前的进程中,而且不得是分离线程
void **status //线程tid所执行的函数返回值(返回值地址需要保证有效),其中status可以为NULL
);
属性对象的初始化于销毁
pthread_attr_init()函数用于对线程属性对象的初始化
int pthread_attr_init(pthread_attr_t *attr);
pthread_attr_destroy()函数用于对线程属性对象的去初始化
int pthread_attr_destroy(pthread_attr_t *attr);
互斥锁、死锁
对互斥量进行加锁和解锁的函数:
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
进程的连接
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define NUM_THREADS 4
void *thread_func(void *index) { /* 线程函数 */
int i;
long tid;
double result=0.0;
tid = (long)index;
printf("Thread %ld starting...\n",tid);
for (i=0; i<1000000; i++) {
result = result + sin(i) * tan(i); /* 进行数学运算 */
}
printf("Thread %ld done. Result = %e\n",tid, result);
pthread_exit((void*) index); /* 带计算结果退出 */
}
int main (int argc, char *argv[]) {
pthread_t tid_array[NUM_THREADS];
int err;
long index;
void *status;
for(index=0; index<NUM_THREADS; index++) {
printf("Main: creating tid_array %ld\n", index);
err = pthread_create(
&tid_array[index],
NULL,
thread_func,
(void *)index
); /* 创建线程 */
if (err) {
printf("ERROR; return code from pthread_create() is %d\n", err);
exit(-1);
}
}
for(index=0; index<NUM_THREADS; index++) {
err = pthread_join(
tid_array[index],
&status
); /*等待线程终止,并获取返回值*/
if (err) {
printf("ERROR; return code from pthread_join() is %d\n", err);
exit(-1);
}
printf("Main: completed join with tid_array %ld having a status of %ld\n",index,(long)status);
}
printf("Main: program completed. Exiting.\n");
pthread_exit(NULL);
}