标签: mutex

使用 VxWorks 反转安全互斥体时为什么需要 SEM_PRIORITY_Q?

在 VxWorks 中,我使用 SEM_INVERSION_SAFE 选项创建互斥体,以防止优先级反转问题。
手册说我还必须使用 SEM_PRIORITY_Q 选项。这是为什么?

mutex semaphore vxworks

0
推荐指数
1
解决办法
2007
查看次数

互斥属性 PTHREAD_PROCESS_SHARED 反转逻辑?

这是我上一个问题( pthread mutex (un)locking over differentthreads )的后续问题。我对如何处理这里的问题和答案感到困惑,所以我重新尝试:o)

我试图通过进程和线程处理互斥体,并使用互斥体属性 PTHREAD_PROCESS_SHARED 来安排它。我添加了一个小示例(基于我上一篇文章中 Paolo 的示例),它演示了我的问题:

#include <stddef.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <semaphore.h>

pthread_mutex_t m;
sem_t s1, s2;

void print(const char *s, int err)
{
    printf("%s %d %s\n", s, err, strerror(err));
}

void *start_t1(void *arg)
{
    sem_wait(&s1); // <-t2
    print("t1: unlock ", pthread_mutex_unlock(&m));
    sem_post(&s2); //->t2
}

void *start_t2(void *arg)
{
    sem_wait(&s2); // <-main
    print("t2: lock ", pthread_mutex_lock(&m));
    sem_post(&s1); // ->t1

    sem_wait(&s2); // <-t1
    sem_post(&s1); // ->main
}

void main(void)
{
    pthread_mutexattr_t …
Run Code Online (Sandbox Code Playgroud)

attributes mutex shared pthreads

0
推荐指数
1
解决办法
6920
查看次数

多个互斥锁如何工作?

我正在学习 POSIX 线程,我的教授已经开始教授第一个读写器问题。这是我关于解决问题的伪代码(仅适用于第一种情况:读者的偏好)。

semaphore rw_mutex = 1; /* semaphore common to both reader & writer */
semaphore mutex = 1; /* semaphore for reading (reader lock) */
int read_count = 0; /* track number of readers in CS */


Writer:
do {
lock(rw_mutex);
/* ensure no writer or reader can enter */
...
/* writing is performed */
...
unlock(rw_mutex);
/* release lock */
} while (true);


Reader:
do
{
lock(mutex);
/* first update read_count atomically */
read_count++;
if (read_count …
Run Code Online (Sandbox Code Playgroud)

c linux multithreading mutex pthreads

0
推荐指数
1
解决办法
1万
查看次数

如何在C中使用pthread来防止同时读写磁盘上的文件?

我正在编写一个程序,它有一个写入线程和几个读取线程,用于写入/读取磁盘上的文件。我希望写入/读取不会同时发生。我发现了很多使用pthread互斥锁在写入/读取期间保护内存阵列的示例,例如将受保护的内存数组声明为易失性。

volatile int array[NUMBER];
pthread_mutex_t locks[NUMBER];

pthread_mutex_lock(&locks[index]);
array[acct] -= SOME_NUMBER;
pthread_mutex_unlock(&locks[index]);
Run Code Online (Sandbox Code Playgroud)

但我找不到使用 pthread 保护磁盘上文件的示例。

volatile FILE* array[NUMBER]; ??
Run Code Online (Sandbox Code Playgroud)

有人能指出我正确的方向吗?我希望写/读线程不会同时访问磁盘上的文件。

编辑:我阅读了更多内容,根据这篇文章,多线程似乎不适用于磁盘 IO。

c multithreading mutex file pthreads

0
推荐指数
1
解决办法
3679
查看次数

使用锁防护和互斥锁的首选方式是什么

类成员函数将在其or上使用mutexand 。我可以看到这可以通过两种不同的方式来完成。lock_guardcritical sectioncritical data

情况 1: - for 循环内部。lock_guard在每次迭代中构造和销毁。

std::mutex s_mutex;

class Foo {
public:
    void bar() {
        for ( ... ) {
            std::lock_guard<std::mutex> guard( s_mutex );
            // critical section data
        } // lock_guard goes out of scope and releases or unlocks mutex
    }
};
Run Code Online (Sandbox Code Playgroud)

情况 2: -在 for 循环之外。lock_guard创建一次,然后在循环完成后销毁。

std::mutex s_mutex;

class Foo {
public:
    void bar() {
        std::lock_guard<std::mutex> guard( s_mutex );
        for ( ... ) {
            // data …
Run Code Online (Sandbox Code Playgroud)

multithreading mutex locking c++17

0
推荐指数
1
解决办法
1037
查看次数

使用互斥锁和解锁时 Go 测试挂起

我是 GO 的新手,我不得不在我的代码中使用互斥锁/解锁来防止并发访问。但是在我将 Lock/Unlock 添加到我的代码之后,我的测试开始永远运行。我简化了我的用例并添加了类及其测试文件。如果我单独运行测试,一切都运行良好。但是如果我运行整个文件,前两个就完成了,但第三个永远运行。如果我删除锁定/解锁,那么运行将正确执行。

如果有人能指出我在这里做错了什么,那就太好了。

被测代码:

package anything

import (
    "sync"
)

var maxLimit = 5
var Store = Cache{make([]string, 0)}
var mutex = new(sync.RWMutex)

type Cache struct {
    items []string
}

func (cache *Cache) Push(item string) {
    mutex.Lock()
    if len(cache.items) == maxLimit {
        cache.items = append(cache.items[:0], cache.items[1:]...)
    }
    cache.items = append(cache.items, item)
    mutex.Unlock()
}

func (cache *Cache) Get(content string) string {
    mutex.RLock()
    for _, item := range cache.items {
        if item == content {
            return content
        }
    } …
Run Code Online (Sandbox Code Playgroud)

synchronization unit-testing mutex go

0
推荐指数
1
解决办法
164
查看次数

在 Golang 中使用互斥锁还是互斥锁指针?

我有一个代码片段:

type calculation struct{
    sum int
    mutex sync.Mutex
}

func dosomething(c *calculation , wg *sync.WaitGroup) {
    c.mutex.Lock()
    c.sum++
    c.mutex.Unlock()
    wg.Done()
}

func main() {
    t := time.Now()
    c := new(calculation)
    wg := new(sync.WaitGroup)
    for i:=0; i<10000000; i++{
        wg.Add(1)
        go dosomething(c, wg)
    }
    wg.Wait()
    fmt.Println(c.sum)
    fmt.Println(time.Since(t))
}
Run Code Online (Sandbox Code Playgroud)

但我发现使用互斥指针也有效:

type calculation struct{
    sum int
    mutex *sync.Mutex
}

func dosomething(c *calculation , wg *sync.WaitGroup) {
    c.mutex.Lock()
    c.sum++
    c.mutex.Unlock()
    wg.Done()
}

func main() {
    t := time.Now()
    c := &calculation{0, new(sync.Mutex)}
    wg := new(sync.WaitGroup) …
Run Code Online (Sandbox Code Playgroud)

pointers mutex go

0
推荐指数
1
解决办法
160
查看次数

如果在 Golang 中使用 mutex.lock() 锁定函数,如何发回响应?

我有这个功能。

func (s *eS) Post(param *errorlogs.Q) (*errorlogs.Error, *errors.RestErr) {
    //sub := q.Get("sub")
    s.mu.Lock()
    utime := int32(time.Now().Unix())

    // Open our jsonFile
    jsonFile, errFile := getlist(param.Id)
    // if we os.Open returns an error then handle it
    if errFile != nil {
        return nil, errFile
    }

    jsonFile, err := os.Open(dir + "/File.json")
    // if we os.Open returns an error then handle it
    if err != nil {
        return nil, errors.NewNotFoundError("Bad File request")
    }
    // read our opened jsonFile as a byte array.
    byteValue, …
Run Code Online (Sandbox Code Playgroud)

rest concurrency mutex http go

0
推荐指数
1
解决办法
94
查看次数

从 Rust 中的全局 HashMap 获取项目的引用

我正在尝试使用静态 HashMap<String, Object> 来存储一些我想在未来全局使用和修改的数据。我发现声明这样一个全局映射的某种方法是使用 lazy_static 和互斥锁来安全地共享数据。但是,当我想将这些对象作为引用返回时,我遇到了一些所有权问题,就像我在上面的代码中所做的那样:

use std::error::Error;
use std::collections::HashMap;
use std::sync::Mutex;
use super::domain::{Session, SessionRepository}; // object and trait declaration

lazy_static! {
    static ref REPOSITORY: Mutex<HashMap<String, Session>> = {
        let mut repo = HashMap::new();
        Mutex::new(repo)
    };    
}

impl SessionRepository for REPOSITORY {
    fn find(cookie: &str) -> Result<&mut Session, Box<dyn Error>> {
        let mut repo = REPOSITORY.lock()?;
        if let Some(sess) = repo.get_mut(cookie) {
            return Ok(sess);
        }

        Err("Not found".into())
    }
}
Run Code Online (Sandbox Code Playgroud)

所以问题是:有没有办法正确地做到这一点?为了达到这种行为,我可以使用 Rust 中的任何设计模式吗?

非常感谢!

static mutex hashmap rust lazy-static

0
推荐指数
1
解决办法
45
查看次数

Mutex ApplicationException when using async/await

I am trying to get the response from a url, and when I use the await and async in my function, my Mutex throws an error.

Error output :

System.ApplicationException
Object synchronization method was called from an unsynchronized block of code.
 at System.Threading.Mutex.ReleaseMutex()
Run Code Online (Sandbox Code Playgroud)

Code :

private async void getData ()
{
    _mutex.WaitOne();

    try
    {
        string url = "https://urllink.com";
        HttpClient client = new HttpClient();
        string response = await client.GetStringAsync(url);
    }
    catch (Exception e)
    {
        // TODO
        throw e;
    }
           
    _mutex.ReleaseMutex();
}
Run Code Online (Sandbox Code Playgroud)

c# mutex asynchronous httpclient async-await

0
推荐指数
1
解决办法
56
查看次数