|
楼主 |
发表于 2006-2-21 19:15:59
|
显示全部楼层
写了一个程序,麻烦大家看看有些什么不成熟的地方
#include <mysql.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
char *query;
int t,r;
pthread_mutex_t my_mutex;
pthread_mutex_init(my_mutex);
void Myupdate();
void Myupdate2();
void Myselect();
int main()
{
pthread_t thread1,thread3,thread2;
int iret1,iret2,iret3;
mysql_init(&mysql);
if (!mysql_real_connect(&mysql,"localhost", "test", "test", "test",0,NULL,0))
{
printf( "Error connecting to database: %s\n",mysql_error(&mysql));
}
else printf("Connected...\n");
iret1= pthread_create( &thread1, NULL, Myupdate, NULL);
iret2= pthread_create( &thread2, NULL, Myupdate2, NULL);
iret3= pthread_create( &thread3, NULL, Myselect, NULL);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
pthread_join( thread3, NULL);
mysql_close(&mysql);
return 0;
}
void Myselect()
{ pthread_mutex_lock(&my_mutex);
query = "select * from ttable";
t = mysql_real_query(&mysql,query,(unsigned int) strlen(query));
if (t)
{
printf("Error making query: %s\n",
mysql_error(&mysql));
}
else printf("[%s] made...\n", query);
res = mysql_store_result(&mysql);
while(row = mysql_fetch_row(res))
{
for(t=0;t<mysql_num_fields(res);t++)
{
printf("%s ",row[t]);
}
printf("\n");
}
printf("mysql_free_result...\n");
pthread_mutex_unlock(&my_mutex);
mysql_free_result(res);
}
void Myupdate()
{
int x;
for(x=0;x<10;x++)
{
pthread_mutex_lock(&my_mutex);
query = "insert into ttable(id, value) values(1, 'Update from thread 1')";
t = mysql_real_query(&mysql,query,(unsigned int) strlen(query));
if (t)
{
printf("Error making query: %s\n",
mysql_error(&mysql));
}
else printf("[%s] made...\n", query);
pthread_mutex_unlock(&my_mutex);
}
}
void Myupdate2()
{
int x;
for(x=0;x<10;x++)
{ pthread_mutex_lock(&my_mutex);
query = "insert into ttable(id, value) values(2, 'Update from thread 2')";
t = mysql_real_query(&mysql,query,(unsigned int) strlen(query));
if (t)
{
printf("Error making query: %s\n",
mysql_error(&mysql));
}
else printf("[%s] made...\n", query);
pthread_mutex_unlock(&my_mutex);
}
} |
|