现在的位置: 首页 > 综合 > 正文

linux下C语言编程5-多线程编程

2013年02月19日 ⁄ 综合 ⁄ 共 2358字 ⁄ 字号 评论关闭

Linux系统下的多线程遵循POSIX线程接口,称为pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,编译需要在后面加-lpthread。

关于多线程,主要有以下几个过程:

1,创建线程

2,各个线程的执行

3,等待线程的结束

涉及的线程函数主要有:

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

函数有4个参数:第一个参数为指向线程标识符的指针。第二个参数用来设置线程属性。第三个参数是一个函数指针(有关函数指针,看这里),指向线程运行函数的起始地址。最后一个参数是函数指针所需要的参数。

注意:pthread_create函数返回0表示成功。另外如果函数指针需要多个参数的话,就将这些参数做成某个结构体,作为第4个参数。如果有返回值的话,也可将返回值的指针回写到第4个参数中。

2,pthread_join()等待一个线程的结束。pthread_exit()用于线程退出,可以指定返回值,以便其他线程通过pthread_join()函数获取该线程的返回值。

线程的应用:并行数据库的查询

假设我们有3台计算机A, B, C,每台均安装PG数据库,通过网络连接。我们可以通过多线程将查询SQL广播出去,A,B,C并行查询,最终返回各自的结果。如果没有多线程,而只是用了个循环,那么我们获取结果的过程将是顺序的,即等A的结果返回后才能查询B,B结束后查询C,效率低下。

代码如下:

//最多支持MAX个线程
#define MAX 16

/**** 多线程 ******/
typedef struct PDthread
{
	char *host;	// IP
	int port;	// 端口
	char *dbname;	// 数据库名
	char *query;	// SQL语句
	void *rst;		// 查询结果
}PDthread;

typedef struct Nodes
{
	int count;	// 实际上的节点数量count<=MAX
	char host[MAX][32];
	int port[MAX];
}Nodes;
/* 线程的执行过程,参数m为PDthread结构 */
void *PDthreadSelect(void *m)
{
	PDthread *p = (PDthread *)m;

	p->rst = (void *)ExecuteQuery(p->host, p->port, p->dbname, p->query);

	pthread_exit(NULL);
	return NULL;
}

/* 创建多个线程,1个node对应1个线程
 * 输出:thread[], pdthread
 * 输入:node, dbname, query, 这些值写到pdthread变量中,传递给函数PDthreadSelect(因为此函数只能有一个参数)
 */
void PDthreadCreate(pthread_t thread[], PDthread *pdthread, Nodes *node, char *dbname, char *query)
{
	int tmp;
	int i;
	PDthread *p;
	for (i=0; i<node->count; i++)
	{
		// 把Nodes作为PDthread的一部分
		p = pdthread + i;
		p->host = node->host[i];
		p->port = node->port[i];
		p->dbname = dbname;
		p->query = query;
		tmp = pthread_create(&thread[i], NULL, PDthreadSelect, p);
		if (tmp != 0)
			printf("PDthreadCreate: 线程%d创建失败!/n", i);
		else
			printf("PDthreadCreate: 线程%d被创建/n", i);
	}
}

void PDthreadWait(pthread_t thread[], int count)
{
	// 等待线程结束
	int i;
	for (i=0; i<count; i++)
	{
		if (thread[i] != 0)
		{
			pthread_join(thread[i],NULL);
			printf("线程%d已经结束/n", i);
		}
	}
}

int main()
{
	Nodes node;
	node.count = 3;
	strcpy(node.host[0], "192.168.0.1");
	node.port[0] = 5432;
	strcpy(node.host[1], "192.168.0.2");
	node.port[1] = 5432;
	strcpy(node.host[2], "192.168.0.3");
	node.port[2] = 5432;

	
	// 使用多线程去获取数据
	pthread_t thread[MAX];
	memset(&thread, 0, sizeof(thread));

	// 获取结果
	PDthread *pdthread = (PDthread *)malloc(node.count * sizeof(PDthread));
	PDthreadCreate(thread, pdthread, &node, "database", "SELECT * FROM student");
	PDthreadWait(thread, node.count);
	
	// 返回结果存储在pdthread->rst
	
	return 0;
}

 编译命令:gcc -I/usr/local/pgsql/include -o th th.c -L/usr/local/pgsql/lib -lpq -lpthread,因为使用了libpq库。

函数ExecuteQuery在上一篇有介绍,linux下C语言编程3-连接PostgreSQL

抱歉!评论已关闭.