第十一章 线程

本文详细介绍了线程管理的基础知识,包括线程的创建、标识、终止及同步机制。通过具体的示例代码展示了如何使用pthread库进行线程的创建、获取线程ID、线程退出及状态获取等功能,并深入探讨了互斥量、读写锁、条件变量等多种同步手段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 线程标识

  int pthread_equal(pthread_t tid1, pthread_t tid2); //线程ID相等的话,返回非0;否则返回0。

  pthread_t pthread_self(void); //返回调用线程的线程ID


2. 线程创建

  int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void*), void *restrict arg);

<span style="font-size:18px;">#include "apue.h"
#include <pthread.h>

pthread_t ntid;

void printids(const char  *s)
{
	pid_t pid;
	pthread_t tid;
	
	pid = getpid();
	tid = pthread_self();
	printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long)pid, (unsigned long)tid, (unsigned long)tid);
}

void *thr_fn(void *arg)
{
	printids("new thread: ");
	return ((void*)0);
}

int main(void)
{
	int err;

	err = pthread_create(&ntid, NULL, thr_fn, NULL);

	if(err != 0)
		err_exit(err, "can't create thread");
	printids("main thread: ");
	sleep(1);
	exit(0);
}
/***********************************************************
main thread:  pid 2844 tid 140306390484800 (0x7f9ba0908740)
new thread:  pid 2844 tid 140306382173952 (0x7f9ba011b700)
***********************************************************/
</span>

3. 线程终止

  void pthread_exit(void *rval_ptr);

  int pthread_join(pthread_t thread, void **rval_ptr); 

<span style="font-size:18px;">#include "apue.h"
#include <pthread.h>

void* thr_fn1(void *arg)
{
	printf("thread 1 returning\n");
	return ((void*)1);
}

void* thr_fn2(void *arg)
{
	printf("thread 2 exiting\n");
	pthread_exit((void*)2);
}

int main(void)
{
	int err;
	pthread_t tid1, tid2;
	void *tret;	

	err = pthread_create(&tid1, NULL, thr_fn1, NULL);
	if(err != 0)
		err_exit(err, "can't create thread 1");
	err = pthread_create(&tid2, NULL, thr_fn2, NULL);
	if(err != 0)
		err_exit(err, "can't create thread 2");
	
	err = pthread_join(tid1, &tret);
	if(err != 0)
		err_exit(err, "can't join with thread 1");
	printf("thread 1 exit code %ld\n", (long)tret);
	err = pthread_join(tid2, &tret);
	if(err != 0)
		err_exit(err, "can't join with thread 2");
	printf("thread 2 exit code %ld\n", (long)tret);
	exit(0);
}
/*********************
thread 2 exiting
thread 1 returning
thread 1 exit code 1
thread 2 exit code 2
*********************/</span>
  当一个线程通过调用pthread_exit退出或者简单地从启动例程中返回时,进程中的其他线程可以通过调用pthread_join函数获得该线程的退出状态。


  int pthread_cancel(pthread_t tid);  //请求取消同一进程中的其它线程

  线程处理程序:

  void pthread_cleanup_push(void (*rtn)(void *), void *arg);

  void pthread_cleanup_pop(int execute); 

<span style="font-size:18px;">#include "apue.h"
#include <pthread.h>

void cleanup(void *arg)
{
	printf("cleanup: %s\n", (char *)arg);
}

void *thr_fn1(void *arg)
{
	printf("thread 1 start\n");
	pthread_cleanup_push(cleanup, "thread 1 first handler");
	pthread_cleanup_push(cleanup, "thread 1 second handler");
	printf("thread 1 push complete\n");
	if(arg)
		return ((void *)1);
	pthread_cleanup_pop(0);
	pthread_cleanup_pop(0);
	return ((void *)1);
}

void *thr_fn2(void *arg)
{
	printf("thread 2 start\n");
	pthread_cleanup_push(cleanup, "thread 2 first handler");
	pthread_cleanup_push(cleanup, "thread 2 second handler");
	printf("thread 2 push complete\n");
	if(arg)
		pthread_exit((void *)2);
	pthread_cleanup_pop(0);
	pthread_cleanup_pop(0);
	pthread_exit((void *)2);
}

int main(void)
{
	int err;
	pthread_t tid1, tid2;
	void *tret;

	err = pthread_create(&tid1, NULL, thr_fn1, ((void *)1));
	if(err != 0)
		err_exit(err, "can't create thread 1");
	err = pthread_create(&tid2, NULL, thr_fn2, ((void *)1));
	if(err != 0)
		err_exit(err, "can't create thread 2");
	
	err = pthread_join(tid1, &tret);
	if(err != 0)
		err_exit(err, "can't join thread 1");
	printf("thread 1 exit code %ld\n", (long)tret);
	err = pthread_join(tid2, &tret);
	if(err != 0)
		err_exit(err, "can't join thread 2");
	printf("thread 2 exit code %ld\n", (long)tret);
	exit(0);
}
/********************************
thread 2 start
thread 2 push complete
cleanup: thread 2 second handler
cleanup: thread 2 first handler
thread 1 start
thread 1 push complete
thread 1 exit code 1
thread 2 exit code 2
********************************/</span>


4. 线程同步

  i. 互斥量

    int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict atrr);

    int pthread_mutex_destroy(pthread_mutex_t *mutex);


    int pthread_mutex_lock(pthread_mutex_t *mutex);

    int pthread_mutex_trylock(pthread_mutex_t *mutex);

    int pthread_mytex_unlock(pthread_mutex_t *mutex);

  

  ii. 避免死锁


  iii. pthread_mutex_timedlock函数(类似于pthread_mutex_lock,不过设置了时间)

    int pthread_mutex_timedlock(pthread_mutex_t *restrict mutex, const struct timespec *restrict tsptr);

<span style="font-size:18px;">#include "apue.h"
#include <pthread.h>

int main(void)
{
	int err;
	struct timespec tout;
	struct tm *tmp;
	char buf[64];
	pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

	pthread_mutex_lock(&lock);
	printf("mutex is locked\n");
	clock_gettime(CLOCK_REALTIME, &tout);
	tmp = localtime(&tout.tv_sec);
	strftime(buf, sizeof(buf), "%r", tmp);
	printf("current time is %s\n", buf);
	tout.tv_sec += 10;
	err = pthread_mutex_timedlock(&lock, &tout);
	clock_gettime(CLOCK_REALTIME, &tout);
	tmp = localtime(&tout.tv_sec);
	strftime(buf, sizeof(buf), "%r", tmp);
	printf("current time is %s\n", buf);
	if(err == 0)
		printf("mutex locked again!\n");
	else
		printf("can't lock mutex again:%s\n", strerror(err));
	exit(0);
}
/******************************************
mutex is locked
current time is 07:25:23 PM
current time is 07:25:33 PM
can't lock mutex again:Connection timed out
******************************************/
</span>


  iX. 读写锁
    使用之前必须初始化,在释放它们底层的内存之前必须销毁。

    int pthread_rwlock_init(pthread_rwlock_t *restric rwlock, const pthread_rwlockattr_t *restrict attr);

    int pthread_rwlock_destory(pthread_rwlock_t *rwlock);

    

    int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);

    int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);

    int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);


    int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);

    int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);


  X. 带有超时的读写锁

    int pthread_rwlock_timerdlock(pthread_rwlock_t *restrict rwlock, const struct timespec *restrict tsptr);

    int pthread_rwlock_timewrlock(pthread_rwlock_t *restrict rwlock, const struct timespec *restrict tsptr);


  Xi. 条件变量

    在使用条件变量之前,必须要初始化。

    int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);

    int pthread_cond_destroy(pthread_cond_t cond);


    int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);

    int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict tsptr);


    int pthread_cond_signal(pthread_cond_t *cond); //唤醒一个等待该条件的线程

    int pthread_cond_broadcast(pthread_cond_t *cond);  //唤醒等待该条件的所有线程

    一定要在改变条件状态以后再给线程发信号。

  

  Xii. 自旋锁(与互斥量接口类似,mutex换成spin)

    用于锁被持有时间段,而线程并不希望在重新调度上话费太多的成本。

    

  Xiii. 屏障(用户协调多个线程并行工作的同步机制)

    int pthread_barrier_init(pthread_barrier_t *restrict barrier, const pthread_barrierattr_t *restrict attr, unsigned int count); //对屏障初始化

    int pthread_barrier_destroy(pthread_barrier_t *barrier); 

    int pthread_barrier_wait(pthread_barrier_t *barrier); 

<span style="font-size:18px;">#include "apue.h"
#include <pthread.h>
#include <limits.h>
#include <sys/time.h>

#define NTHR 8
#define NUMNUM 800000L
#define TNUM (NUMNUM/NTHR)

long nums[NUMNUM];
long snums[NUMNUM];

pthread_barrier_t b;

/*
#ifdef SOLARIS
#define heapsort qsort
#else
extern int heapsort(void *, size_t, size_t, int (*)(const void*, const void*));
#endif
*/


int complong(const void *arg1, const void *arg2)
{
	long l1 = *(long *)arg1;
	long l2 = *(long *)arg2;
	
	if(l1 == l2)
		return 0;
	else if(l1 < l2)
		return -1;
	else
		return 1;
}

void* thr_fn(void *arg)
{
	long idx = (long)arg;
	qsort(&nums[idx], TNUM, sizeof(long), complong);
	pthread_barrier_wait(&b);
	
	return ((void *)0);
}

void merge()
{
	long idx[NTHR];
	long i, minidx, sidx, num;

	for(i = 0; i < NTHR; i ++)
		idx[i] = i * TNUM;
	
	for(sidx = 0; sidx < NUMNUM; sidx ++){
		num = LONG_MAX;
		for(i = 0; i < NTHR; i ++) {
			if((idx[i] < (i + 1) * TNUM) && (nums[idx[i]] < num)){
				num = nums[idx[i]];
				minidx = i;
			}
		}
		snums[sidx] = nums[idx[minidx]];
		idx[minidx] ++;
	}	
}

int main()
{
	unsigned long i;
	struct timeval start, end;
	long long startusec, endusec;
	double elapsed;
	int err;
	pthread_t tid;

	srandom(1);
	for(i = 0; i < NUMNUM; i ++)
		nums[i] = random();

	gettimeofday(&start, NULL);
	pthread_barrier_init(&b, NULL, NTHR + 1);
	for(i = 0; i < NTHR; i ++){
		err = pthread_create(&tid, NULL, thr_fn, (void *)(i * TNUM));
		if(err != 0)
			err_exit(err, "can't create pthread");
	}
	pthread_barrier_wait(&b);
	merge();
	gettimeofday(&end, NULL);
	
	startusec = start.tv_sec * 1000000 + start.tv_usec;
	endusec = end.tv_sec * 1000000 + end.tv_usec;
	elapsed = (double)(endusec - startusec) / 1000000.0;
	printf("sort took %.4f seconds\n", elapsed);
//	for(i = 0; i < NUMNUM; i ++)
//		printf("%ld\n", snums[i]);
	exit(0);
}
</span>
    对实际输出而言,速度很快,没什么效果...

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值