UNIX 网络编程之线程

 概述:

   实现并发服务器通常都是父进程accept一个链接,而后fork一个子进程,该子进程处理与该链接对端的客户之间的通讯。可是fork是昂贵,耗资源和时间。而线程是轻量级线程,它的建立比进程的建立块10-100倍。在同一进程内除了共享全局变量外还共享:服务器

 大多数数据;进程指令; 打开的文件; 信号处理函数信号处置; 当前工做目录;用户ID和组ID多线程

不过每一个线程有各自的资源:‘并发

 线程ID; 寄存器集合了栈了errno; 信号掩码; 优先级函数

基本线程函数:建立和终止

  pthread_create函数spa

  #include <pthread.h>线程

  int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*func)(void *), void *arg);code

 一个进程的每一个线程都由一个线程ID标识。每一个线程有不少属性,好比优先级大小,初始栈大小,是否应该成为一个守护线程等等进程


  pthread_join函数资源

 

 #include <pthread.h>同步

  int pthread_join(pthread_t *tid, void **status);

  该函数相似与waitpid


  pthread_self函数

   #include <pthread.h>
  int pthread_self(void);

  每一个线程使用pthread_self得到自身的线程ID


 pthread_detach函数

 

 #include <pthread.h>

  int pthread_detach(pthread_t tid);

  一个线程或者是可汇合的,或者是脱离的。当一个可汇合的线程终止时,它的线程ID和退出状态将留存到另外一个线程对它调用pthread_join。脱离的线程像守护线程,当他们终止时,全部相关资源都被释放.


 pthread_exit函数

  

 #include <pthread.h>

  int pthread_exit(void *status);

结束一个线程


互斥锁的使用

多线程程序的经典问题:多个线程同时修改一个共享变量(如全局变量)

 

#include <pthread.h>
#include <stdio.h>

int counter;
void *doit(void*);

int main(int argc, char **argv)
{
	pthread_t tidA, tidB;

	pthread_create(&tidA, NULL, &doit, NULL);
	pthread_create(&tidB, NULL, &doit, NULL);

	pthread_join(tidA, NULL);
	pthread_join(tidB, NULL);
	return 0;
}

void *doit(void * arg)
{
	int i, val;
	for(i=0; i<10; i++)
	{
		val = counter;
		printf("counter is %d\n", val+1);
		counter = val+1;
	}
	return NULL;
}

上面程序的运行结果并非咱们想要的结果,由于线程的运行是并发运行的,也就是说counter值的修改的结果是不定的,如下为运行结果

 


因此咱们应该引入同步机制,首先使用互斥量实现

 

#include <pthread.h>
#include <stdio.h>

int counter;
pthread_mutex_t counter_mutex;

void *doit(void*);

int main(int argc, char **argv)
{
	pthread_t tidA, tidB;

	pthread_create(&tidA, NULL, &doit, NULL);
	pthread_create(&tidB, NULL, &doit, NULL);

	pthread_join(tidA, NULL);
	pthread_join(tidB, NULL);
	return 0;
}

void *doit(void * arg)
{
	
	int i, val;
	for(i=0; i<10; i++)
	{
		pthread_mutex_lock(&counter_mutex);
		val = counter;
		printf("counter is %d\n", val+1);
		counter = val+1;
		pthread_mutex_unlock(&counter_mutex);
	}
	return NULL;
}


使用在对counter值进行修改以前进行上锁操做,修改以后,进行解锁操做

 

相关文章
相关标签/搜索