关于多线程的思考

来源:互联网 发布:淘宝上下架时间几点好 编辑:程序博客网 时间:2024/06/06 14:12

   关一段时间比较了一下python和perl的多线程,惊讶的发现,perl的多线程多够充分利用多核CPU的优势,而python的多线核则不能充分利用多核CPU,当时以为受限制于python的GIL锁,python,在一个python解释器进程的情况下,不可能充分利用多核,而当时觉得perl能够把其它的核心利用起来(通过HTOP命令查看),很神奇,也不知道它是怎么实现的。

   不过当时没有对perl的线程进行同步,所以就忽略了。

   今天需要处理一些数据,想到了perl,想弄个多线程版本的,发现一个秘密,原来之前perl能充分利用多核,是因为——默认情况下,perl在建立线程的时候,对每一份数据多进行了私有的拷贝,一旦需要对变量进行互斥访问时,就不能利用多核了,也就是说,只要用了threads::shared这个东东,就跟python查不多了,因为其中也会用到一个全局锁类似的东西。。

   好吧,我想,那就直接用C语言吧,一了百了,看代码。下面的代码用于从mysql中读出数据,进行处理。

#include <stdio.h>#include <stdlib.h>#include <mysql/mysql.h>#include <pthread.h>#include <string.h>#include <sys/time.h>#include <time.h>/* define the number of worker thread */#define NUM 1/* worker thread */pthread_t worker[NUM];pthread_mutex_t mut;MYSQL_RES *res;void *worker_thread();void thread_create();void thread_wait();int main(int argc,char **argv){clock_t begin,end;double cost;MYSQL *conn_ptr;begin=clock();conn_ptr=mysql_init(NULL);if(!conn_ptr){fprintf(stderr,"mysql_init failed\n");exit(-1);}mysql_options(conn_ptr,MYSQL_SET_CHARSET_NAME,"utf8");conn_ptr=mysql_real_connect(conn_ptr,"localhost","xxxxx","******","abc",0,NULL,0); /* 修改成你的参数 */if(!conn_ptr){printf("connection failed:%s \n",mysql_error(conn_ptr));exit(-1);}if(mysql_query(conn_ptr,"select * from ******")){ /* 修改成你的参数 */fprintf(stderr,"%s\n",mysql_error(conn_ptr));exit(-1);}res=mysql_store_result(conn_ptr);thread_create();thread_wait();mysql_free_result(res);mysql_close(conn_ptr);end=clock();cost=(double)(end-begin);printf("the cost is %lf \n",cost);return 0;}void *worker_thread(){MYSQL_ROW row;do{pthread_mutex_lock(&mut);row=mysql_fetch_row(res);pthread_mutex_unlock(&mut);if(row!=NULL){//printf("%s\n",row[0]);}}while(row!=NULL);}void thread_create(){memset(&worker,0,sizeof(worker));int i,ret;for(i=0;i<NUM;i++){if((ret=pthread_create(&worker[i],NULL,worker_thread,NULL))!=0){printf("create thread %d failed...\n",i);}else{printf("create thread %d ...\n",i);}}}void thread_wait(){int i;for(i=0;i<NUM;i++){if(worker[i]!=0){pthread_join(worker[i],NULL);printf("thread %d terminated...\n",i);}}}

其中,NUM可以指定想要的线程数量,发现随着NUM增大,程序执行时间越长。。


我于是又郁闷了,为啥多线程反而使速度降了下来呢??

其实想想就明白了,我这里的代码,仅仅是从数据库中把数据读出来,没有作任何处理。

读出的总记录数一样,如果是多线程,越来,维护线程之间的同步的开销越大,显然时间越长了。

所以这就了然了,如果,我们对读出的数据需要作耗费时间的处理的话,这个时候,我想多线程的优势就应该体现出来了吧。

原创粉丝点击