PHP code example of hokoo / wp-lock

1. Go to this page and download the library: Download hokoo/wp-lock library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hokoo / wp-lock example snippets


// Top-up function that is not thread-safe
public function topup_user_balance( $user_id, $topup ) {
	$balance = get_user_meta( $user_id, 'balance', true );
	$balance = $balance + $topup;
	update_user_meta( $user_id, 'balance', $balance );
	return $balance;
}

// A thread-safe version of the above topup function.
public function topup_user_balance( $user_id, $topup ) {
	$user_balance_lock = new WP_Lock( "$user_id:meta:balance" );
	$user_balance_lock->acquire( WP_Lock::WRITE );

	$balance = get_user_meta( $user_id, 'balance', true );
	$balance = $balance + $topup;
	update_user_meta( $user_id, 'balance', $balance );

	$user_balance_lock->release();

	return $balance;
}

use iTRON\WP_Lock;

$lock = new WP_Lock\WP_Lock( 'my-lock' );

$lock->acquire( WP_Lock::READ, true, 0 );
// do something, and then
$lock->release();

public function acquire( $level = self::WRITE, $blocking = true, $expiration = 30 )

if ( $lock->acquire( WP_Lock::READ, false, 0 ) ) {
    // do something, and then
    $lock->release();
}

$another_lock = new WP_Lock\WP_Lock( 'my-lock' );

if ( $another_lock->acquire( WP_Lock::READ, false, 0 ) ) {
    $lock->lock_exists( WP_Lock::READ ); // true
    $lock->lock_exists( WP_Lock::WRITE ); // false
    
    $another_lock->release();
}

if ( $another_lock->acquire( WP_Lock::WRITE, false, 0 ) ) {
    $lock->lock_exists( WP_Lock::READ ); // true
    $lock->lock_exists( WP_Lock::WRITE ); // true
    
    $another_lock->release();
}