swoole-src: Table object does not work across threads

I can confirm that table objects do not work across threads. Documents should be updated to clarify.

As stated in https://www.swoole.co.uk/docs/modules/swoole-table

Why to use swoole table

  • High performance, the single thread read/write speed is more than 2 millions per second.
  • Can be used by multiple threads or processes.
  • In application counters storage.

Code I used

<?php

class A extends Thread {
    public $table;
    public function __construct($table) {
        $this->table = $table;
    }
    public function run() {
        if (!$this->table->set('test_key', array('id' => 1))) {
            echo "could not set\n";
        }
    }
}

class B extends Thread {
    public $table;
    public function __construct($table) {
        $this->table = $table;
    }
    public function run() {
        $ret = $this->table->get('test_key');
        if (!($ret and is_array($ret) and $ret['id'] == 1)) {
            echo "some other error\n";
        }
    }
}

$table = new swoole_table(65536);
$table->column('id', swoole_table::TYPE_INT);
$table->create();

$a = new A($table);
$a->start();

$b = new B($table);
$b->start();

$b->join();

expected results: get ‘test_key’ from table

actual results:

PHP Fatal error:  Uncaught Error: Call to a member function set() on null in /home/jason/chan_thread.php:9
Stack trace:
#0 [internal function]: A->run()
#1 {main}
  thrown in /home/jason/chan_thread.php on line 9
PHP Fatal error:  Uncaught Error: Call to a member function get() on null in /home/jason/chan_thread.php:22
Stack trace:
#0 [internal function]: B->run()
#1 {main}
  thrown in /home/jason/chan_thread.php on line 22

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 16 (2 by maintainers)

Most upvoted comments

I think all this comes from the confusion of swoole built in threads (they have that concept too, look at the source code) and the php7 threads?

Perhaps the document should be updated to clarify this. I have a hunch that with coroutine support there is no gain with supporting the php7 threads at the same time. Perhaps I’m wrong.

The swoole_table is not thread-safety. No compatibility with pthreads has been considered since the design

Thats not the way table works, i guess ?

https://github.com/swoole/swoole-src/issues/2034#issuecomment-429503111

But, i would like to have some additional explanation about this, too 😊