关于mysql多线程访问串行与并行的问题
InitConnection (4); //初始化连接池,放入4个mysql句柄
for(int i=0;i<4;i++)
{
mysql = GetConnection (); //获取一个MYSQL句柄
Insert (mysql ,"insert children values(6,'yantai',40)"); //执行插入
}
我想问下这个程序到底是并行,还是串行的?
InitConnection (4);
for(int i=0; i<4;i ++)
{
mysql = GetConnection ();
for( int i = 0; i
{
pthread_create(&thread_id [i], NULL, Testinsert ,mysql);
}
for(int i = 0; i
{
pthread_join(thread_id [i], NULL);
}
}
那么这四个连接是并行还是串行?四个连接并行?四个连接并行五次?
InitConnection (4);
for(int i=0; i<1;i ++)
{
mysql = GetConnection ();
for( int i = 0; i
{
pthread_create(&thread_id [i], NULL, Testinsert ,mysql);
}
for(int i = 0; i
{
pthread_join(thread_id [i], NULL);
}
}
这应该是4个连接并行一次,这和第一个程序有区别么?
串行和并行不是太清楚,希望大家点拨一下。谢谢
分享到:
------解决方案--------------------
1.
InitConnection (4); //初始化连接池,放入4个mysql句柄
for(int i=0;i<4;i++)
{
mysql = GetConnection (); //获取一个MYSQL句柄
Insert (mysql ,"insert children values(6,'yantai',40)"); //执行插入
}
没用过这个库。判断是否为串行,就用一个慢速查询语句,很快返回的就是并发执行。
另外就是看返回的方式,如果是并发执行(异步)则要回调函数来获取返回结果,一般比较少见。
所以假设为串行(同步)。
2.InitConnection (4);
for(int i=0; i<4;i ++)
{
mysql = GetConnection ();
for( int i = 0; i
{
pthread_create(&thread_id [i], NULL, Testinsert ,mysql);
}
for(int i = 0; i
{
pthread_join(thread_id [i], NULL);
}
}
那么这四个连接是并行还是串行?四个连接并行?四个连接并行五次?
如果是串行(同步),这么做可能不安全,一般是一个线程一个数据库连接。
3.InitConnection (4);
for(int i=0; i<1;i ++)
{
mysql = GetConnection ();
for( int i = 0; i
{
pthread_create(&thread_id [i], NULL, Testinsert ,mysql);
}
for(int i = 0; i
{
pthread_join(thread_id [i], NULL);
}
}
这应该是4个连接并行一次,这和第一个程序有区别么?
这个不是并行,原因是大循环里包含了pthread_join,它会等子线程执行完成在继续循环。
应该这样:
InitConnection (4);
for(int i=0; i<4;i++){
mysql = GetConnection ();
pthread_create(&thread_id[i], NULL, Testinsert ,mysql);
}
for(int i = 0; i
pthread_join(thread_id[i], NULL);
}