Skip to content

Instantly share code, notes, and snippets.

@hirokuma
Created February 24, 2019 04:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hirokuma/db5921856cc7e1b2409357487237238e to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "lmdb.h"
#define DBDIR "./testdb"
#define DBNAME "name"
static MDB_env *env;
static void *thread_func(void *pArg)
{
int code = (int)pArg; //warningが出るが、気にしない
int rc;
MDB_txn *txn;
MDB_dbi dbi;
MDB_val key, data;
int slp = 0;
unsigned long flags = 0;
switch (code) {
case 1:
sleep(1);
flags = 0;
slp = 10;
break;
case 2:
flags = MDB_RDONLY;
slp = 3;
break;
}
fprintf(stderr, "txn begin: code=%d(%s)\n", code, (flags & MDB_RDONLY ? "rdonly" : "normal"));
rc = mdb_txn_begin(env, NULL, flags, &txn);
if (rc) {
fprintf(stderr, "fail: mdb_txn_begin(%d:%s)\n", code, mdb_strerror(rc));
goto LABEL_EXIT2;
}
rc = mdb_dbi_open(txn, DBNAME, 0, &dbi);
if (rc) {
fprintf(stderr, "fail: mdb_dbi_open(%d:%s)\n", code, mdb_strerror(rc));
mdb_txn_abort(txn);
goto LABEL_EXIT2;
}
printf("sleeping(%d)...\n", code);
sleep(slp);
printf("wake up(%d)\n", code);
switch (code) {
case 1:
key.mv_size = sizeof(code);
key.mv_data = &code;
data.mv_size = sizeof(slp);
data.mv_data = &slp;
rc = mdb_put(txn, dbi, &key, &data, 0);
if (rc == 0) {
fprintf(stderr, "txn commit: code=%d\n", code);
mdb_txn_commit(txn);
} else {
fprintf(stderr, "fail: mdb_put(%d:%s)\n", code, mdb_strerror(rc));
mdb_txn_abort(txn);
}
break;
case 2:
fprintf(stderr, "txn abort: code=%d\n", code);
mdb_txn_abort(txn);
break;
default:
;
}
LABEL_EXIT2:
return NULL;
}
int main(void)
{
int rc;
MDB_txn *txn;
MDB_dbi dbi;
mkdir(DBDIR, 0755);
rc = mdb_env_create(&env);
if (rc) {
fprintf(stderr, "fail: mdb_env_create(%s)\n", mdb_strerror(rc));
}
rc = mdb_env_set_maxdbs(env, 1);
if (rc) {
fprintf(stderr, "fail: mdb_env_set_maxdbs(%s)\n", mdb_strerror(rc));
}
rc = mdb_env_open(env, DBDIR, MDB_FIXEDMAP, 0664);
if (rc) {
fprintf(stderr, "fail: mdb_env_open(%s)\n", mdb_strerror(rc));
goto LABEL_EXIT1;
}
rc = mdb_txn_begin(env, NULL, 0, &txn);
if (rc) {
fprintf(stderr, "fail: mdb_txn_begin(%s)\n", mdb_strerror(rc));
goto LABEL_EXIT1;
}
rc = mdb_dbi_open(txn, DBNAME, MDB_CREATE, &dbi);
if (rc) {
fprintf(stderr, "fail: mdb_dbi_open(%s)\n", mdb_strerror(rc));
mdb_txn_abort(txn);
goto LABEL_EXIT1;
}
mdb_txn_commit(txn);
pthread_t th1;
pthread_create(&th1, NULL, &thread_func, (void *)1);
pthread_t th2;
pthread_create(&th2, NULL, &thread_func, (void *)2);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
LABEL_EXIT1:
mdb_env_close(env);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment