# swoole 内存操作模块

Swoole提供了7个内存操作的模块，在多进程编程中可以帮助开发者实现一些特殊的需求。

建议先提前看下以下官方文档（7个内存操作）

* [Lock](https://wiki.swoole.com/wiki/page/p-lock.html)
* [Buffer](https://wiki.swoole.com/wiki/page/246.html)
* [Table](https://wiki.swoole.com/wiki/page/p-table.html)
* [Atomic](https://wiki.swoole.com/wiki/page/p-atomic.html)
* [mmap](https://wiki.swoole.com/wiki/page/p-mmap.html)
* [Channel](https://wiki.swoole.com/wiki/page/p-channel.html)
* [Serialize](https://wiki.swoole.com/wiki/page/p-serialize.html)

## 进程间通讯-共享内存方式

![](/files/-LfnTFg38Wi9EzCW2fMU)、

在系统内存中开辟一块内存区，分别映射到各个进程的虚拟地址空间中，任何一个进程操作了内存区都会反映到其他进程中，各个进程之间的通信并没有像copy数据一样从内核到用户，再从用户到内核的拷贝。这种方式可以像访问自己的私有空间一样访问共享内存区，是速度最快的一种通信方式。

但是这事这种特性加大了共享内存的编程难度，比如多个进程同时读取到一个数据做操作，容易造成数据的混乱。

## swoole\_table

swoole\_table一个基于共享内存和锁实现的超高性能，并发数据结构。用于解决多进程/多线程数据共享和同步加锁问题,应用代码无需加锁，swoole\_table内置行锁自旋锁，所有操作均是多线程/多进程安全。用户层完全不需要考虑数据同步问题\
。

**创建一个共享内存的table**  <br>

使用swoole共享table非常简单,简单几步就可以创建

1、实例化table并且设置最大行数

```php
$table = new swoole_table(1024);
```

2、指定表格字段，指定表格类型以及长度

```php
$table->column('id', $table::TYPE_INT, 4);
$table->column('name', $table::TYPE_STRING, 64);
$table->column('age', $table::TYPE_INT, 3);
```

3、创建表格

```php
$table->create();
```

4、设置一行数据

```php
$table->set('user', ['id' => 1, 'name'=> 'revin', 'age' => 30]);
```

另外一种方案

```php
$table['user_2'] = [
    'id' => 2,
    'name' => 'revin2',
    'age' => 29,
];
```

5.其他操作

```php
$table->decr('user_2', 'age', 2);
$table->del('user');
```

## 注意事项：

* 1、在swoole\_server->start()之前创建swoole\_table对象。并存入全局变量或者类静态变量/对象属性中，在worker/task进程中获取table对象，并使用。
* 2、只有在swoole\_server->start()之前创建的table对象才能在子进程中使用
* 3、swoole\_table构造方法中指定了最大容量，一旦超过此数据容量将无法分配内存导致set操作失败。所以使用swoole\_table之前一定要规划好数据容量。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/swoole/swoole-ji-chu/jin-cheng-nei-cun-xie-cheng/swoole-nei-cun-cao-zuo-mo-kuai.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
