简体   繁体   English

MySql:如何在存储过程中使用互斥锁

[英]MySql: How do you use mutex/lock in a stored-procedure

I want my function to only run once. 我希望我的功能只运行一次。 Meaning that if many threads call it at the same time, the function will block all threads apart from one and only allow it to run. 这意味着,如果许多线程同时调用它,则该函数将阻塞除一个线程之外的所有线程,并仅允许其运行。

It sounds like you want the stored procedure to do the synchronization. 听起来您想让存储过程进行同步。 Why not just put the synchronization in the application itself. 为什么不将同步放在应用程序本身中呢?

pthread_mutex_lock(&lock);
... Call stored procedure here ..
pthread_mutex_unlock(&lock);

If you need to provide synchronization at the database level, you can use the LOCK and UNLOCK TABLES commands within your stored procedure. 如果需要在数据库级别提供同步,则可以在存储过程中使用LOCK和UNLOCK TABLES命令。 Lock on entry to the procedure and unlock on exit. 在进入该程序时锁定,并在退出时解锁。 Depending on your needs, it may be that you'll want to create a dummy table that is locked and unlocked instead of an actual data table in use by this and other processes. 根据您的需求,可能需要创建一个已锁定和未锁定的虚拟表,而不是此进程和其他进程正在使用的实际数据表。 See here for more details. 有关更多详细信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM