我正在开发一个线程化程序,它读取10个线程中的mysql数据库,并将结果作为每个线程的行数打印出来。所以最终的结果是在命令行上有100行计数。问题是当我运行它时,它有时会给出一个错误,说Can't connect to MySQL server on 'localhost' (111)
有时它会返回一个segmentation fault(core dumped)
我检查了线程,它们也创建正常,没有错误。无法连接到'localhost'上的MySQL服务器(111)
当我创建只有一个线程它完美地罚款给予预期的输出。 No of Rows of 00 - 6
另一件事是我在红帽服务器运行这个和它运作良好,没有错误,但数为wrong.I创建5个线程和第一线52380
是正确的,但对其他人而言,给出了不同的结果结果应该来这样
No of Rows of 00 - 52380
No of Rows of 01 - 53434
No of Rows of 02 - 53333
No of Rows of 03 - 50005
No of Rows of 04 - 48393
但实际结果出来是这样的
No of Rows of 00 - 52380
No of Rows of 00 - 52380
No of Rows of 01 - 52380
No of Rows of 01 - 52380
No of Rows of 01 - 52380
我编译这个使用
gcc main.c -lpthread `mysql_config --cflags --libs`
这个问题会导致什么原因。任何人都可以帮助我请这个。这里是我使用的代码。头文件不在这里给出。它包含数据库详细信息。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "main1.h"
#include <pthread.h>
#include <mysql/mysql.h>
#include <mysql/my_global.h>
int main(int argc, char** argv) {
int threadRet[10], i = 0;
pthread_t * threadT = (pthread_t *) malloc(10 * sizeof (pthread_t));
for (i = 0; i < 10; i++) {
threadRet[i] = pthread_create(&threadT[i], NULL, threadedConnection, &i);
printf("thread %d - thread ret %d\n",i,threadRet[i]);
}
i = 0;
for (i = 0; i < 10; i++) {
pthread_join(threadT[i], NULL);
}
return (EXIT_SUCCESS);
}
void * threadedConnection(void * parr) {
int * j = (int *) parr;
int tableNo=*j;
long int rowCount = 0;
long int totalInserts = 0;
MYSQL *con1 = mysql_init(NULL);
MYSQL_RES *result;
MYSQL_ROW row;
con1[tableNo] = mysql_init(NULL);
if (mysql_real_connect(con1, dataBase1[0], dataBase1[1], dataBase1[2], dataBase1[3], 0, NULL, 0) == NULL) {
fprintf(stderr, "%s\n", mysql_error(con1));
mysql_close(con1);
exit(1);
}
char countQuery[70];
sprintf(countQuery, "SELECT COUNT(*) FROM numberTable where number like '%s%.2d'", "%", *tableNo);
if (mysql_query(con1[tableNo], countQuery)) {
fprintf(stderr, "%s\n", mysql_error(con1));
mysql_close(con1);
exit(1);
}
result = mysql_store_result(con1); //Counting
row = mysql_fetch_row(result[tableNo]); //line
rowCount = strtol((row)[0], NULL, 10); //numbers
totalInserts = rowCount; //numberTable
mysql_free_result(result[tableNo]);
printf("No of Rows of %.2d - %ld\n", tableNo, totalInserts);
mysql_close(con1[tableNo]);
}
问:什么是运行多个线程的目的?问:无关,但为什么您使用弃用的API,而不是[PDO](http://php.net/manual/en/ref.pdo-mysql.php)或[mySqli](http:// php。净/手动/ EN/book.mysqli.php)?看看这里的更多细节:http://php.net/manual/en/mysqlinfo.api.choosing.php – paulsm4
@ paulsm4这是一个应用程序,需要更高的速度。在这个程序中还有另一个没有被开发的进程。计算并插入到另一台mysql服务器。这只是开始部分。 – Laksith
非常重要:1)请不要*针对弃用的“mysql”API编写任何新代码。 2)请不要*期待你的线程中的“printf()'”匹配执行的实际顺序 - 它们不会。 4)检查mySQL配置中的[max_connections](https://dev.mysql.com/doc/refman/5.5/en/too-many-connections.html)。最重要*:请看看你的'mysql_error()'输出,看看你的mySQL错误日志,并且*用一个不错的错误消息*更新你的POST。 – paulsm4