When I use tikv api, and I found it has an option in TxnKV client, then I test it, but I can not find what the difference between optimistic and pessimistic is in tikv?
The test code is this:
func begin() kv.Transaction{
transaction, err := store.Begin()
if err!=nil{
panic(err)
}
return transaction
}
func main() {
pdAddr := os.Getenv("PD_ADDR")
if pdAddr != "" {
os.Args = append(os.Args, "-pd", pdAddr)
}
flag.Parse()
initStore()
k2 := []byte("key2")
v22 := []byte("value22")
v23 := []byte("value22")
testTxn(k2,v22,v23)
}
func testTxn(k2 []byte, v22 []byte, v23 []byte) {
txn1, txn2 := begin(), begin()
txn1.SetOption(kv.Pessimistic, true)
fmt.Println("txn1 after:", txn1.IsPessimistic())
txn2.SetOption(kv.Pessimistic, true)
fmt.Println("txn2 after:", txn2.IsPessimistic())
err := txn1.Set(k2, v22)
if err != nil {
panic(err)
}
err = txn2.Set(k2, v23)
if err != nil {
panic(err)
}
err = txn1.Commit(context.Background())
if err != nil {
panic(err)
}
fmt.Println(get(k2))
err = txn2.Commit(context.Background())
if err != nil {
panic(err)
}
}
No matter whether I set txn1.SetOption(kv.Pessimistic, true)
and txn2.SetOption(kv.Pessimistic, true)
or not, I haven't found the difference between them.
But in tidb or mysql, modify the same records with a pessimistic transaction, it will block.
Such as transaction A:
begin;
updata t1 set col ="value1" where id=1;
transaction B:
begin;
updata t1 set col ="value2" where id=1; //it will block until transaction A commit or rollback
I have two question :
- What's the difference between optimistic and pessimistic in tikv?
- What's the difference between tikv's pessimistic-lock and mysql/tidb's pessimistic-lock?
If anyone has any idea, please share it with me, thanks