多线程开发板

查看代码

线程的创建与终止

创建

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);
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值