what different betweent optimistic and pressimistic in tikv?

when i use tikv api ,and i found it have a option in TxnKV client,then i test it,but i can not find what different between optimistic and pressimistic in tikv? the test code is below:

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, modifiy 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 util transaction A commit or rollback

so i have two question :

  1. what’s different betweent optimistic and pressimistic in tikv?
  2. what’s different betweent tikv’s pressimistic-lock and mysql/tidb’s pressimistic-lock?

If anyone has any idea, pls tell me, thanks

TiDB事务概览
image

tikv 中的乐观事务和悲观事务的区别是什么?

乐观事务模型
采用2PC(两阶段提交)实现,2PC主要分Prewrite和commit这2个阶段。大概的流程是:客户端开启事务,执行DML,客户端发起commit,下面开始2PC的prewrite阶段:TiDB 从当前要写入的数据中选择一个 Key 作为当前事务的 Primary Key,TiDB 并发地向所有涉及的 TiKV 发起 prewrite 请求,TIKV则进行检测后将满足条件的数据加锁。TIDB收到prewrite成功响应,TIDB向PD请求事务commit_ts,下面进入2PC的commit阶段:TIKV收到commit操作并check后执行commit(keys,commit_ts),并且清理prewrite的锁,TIDB收到2PC commit成功的信息并且反馈给客户端。


悲观事务模型
TiDB 在乐观事务模型的基础上支持了悲观事务模型,将上锁的时机提前到进行DML时。TiDB 的悲观锁实现的原理确实如此,在一个事务执行 DML (UPDATE/DELETE) 的过程中,TiDB 不仅会将需要修改的行在本地缓存,同时还会对这些行直接上悲观锁,这里的悲观锁的格式和乐观事务中的锁几乎一致,但是锁的内容是空的,只是一个占位符,待到 Commit 的时候,直接将这些悲观锁改写成标准的 Percolator 模型的锁,后续流程跟乐观模型一样。

你好,你可能有点误解我的意思,我知道TIDB 中悲观事务中提前上锁到DML语句中,我的疑问是,TiKV(不是TiDB) 中的TxnKV client 的txn1.SetOption(kv.Pessimistic, true)的作用,正如我问题中的,开启两个事务txn1, txn2,操作同一个key,另一个事务并没有阻塞(这个是我的疑惑点)。

:sweat_smile:这个等官方回复吧,触及到我的知识盲点了~