标签: locking

如何在多线程应用程序中使用锁?

请检查我的多线程代理检查器代码.它总是检查相同的代理.我想我需要使用锁吗?但是当我使用锁时,它只使用一个线程.但通常它是多线程的.这是什么问题?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading;

namespace ProxyChecker
{
    public partial class Main : Form
    {


        public Main()
        {
            InitializeComponent();

        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            proxyList.Items.Clear();
        }

        private void clearButton2_Click(object sender, EventArgs e)
        {
            checkedList.Items.Clear();

        }

         Thread[] checkerThread;
        int checking;
        int beenChecked;
        private bool isRunning;
        private delegate void filterProxyHandler(int Index, bool Valid);
        static readonly object _locker = new object();


        private …
Run Code Online (Sandbox Code Playgroud)

c# sockets multithreading locking

-1
推荐指数
1
解决办法
168
查看次数

如果对象位于另一个对象内,C# Monitor.Enter 不会锁定

我认为只要对对象的引用或对象本身不改变,Monitor.Enter 就可以对对象的引用起作用。

这是我的简单案例,我有一个名为 QueueManager 的类,其中有一个队列。在操作队列之前,我使用此对象队列来使用 Monitor.Lock 进行锁定。我尝试了在队列对象上调用 Monitor.Lock 的简单测试,但失败了。知道为什么吗?

public class QueueManager
{
    private List<ConversionJob> _jobQueue = new List<ConversionJob>();

    public QueueManager()
    {
    }

    public List<ConversionJob> Queue
    { get { return _jobQueue; } }
}

public class Main
{
    private QueueManager qMgr = new QueueManager();

    public Main()
    {
        try
        {
            Monitor.Enter(qMgr.Queue);
            throw new Exception();
        }
        catch (Exception)
        {
            Monitor.Enter(qMgr.Queue);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这不会死锁!我不明白为什么它不会陷入僵局。我尝试了这个,因为我怀疑锁被盗了,所以我把这个测试代码放进去,我很惊讶。

c# locking object

-1
推荐指数
1
解决办法
1724
查看次数

如何在多个表中锁定插入?

我使用此命令在多行中插入多个记录,如果插入不成功,如何锁定命令和回滚更改?

SqlCommand cmd = new SqlCommand();

        string s = @"

                declare @one_id int; 

                INSERT INTO tbl_one(o1,o2,o3) VALUES(@o1,@o2,@o3);

                set @one_id=SCOPE_IDENTITY();

                INSERT INTO tbl_two(t1,t2,f3) VALUES(@t1,@t2,@one_id);
                INSERT INTO tbl_two(t1,t2,f3) VALUES(@t3,@t4,@one_id);
                INSERT INTO tbl_two(t1,t2,f3) VALUES(@t5,@t6,@one_id);
                ";

        cmd.CommandText =s;
Run Code Online (Sandbox Code Playgroud)

sql sql-server asp.net locking transactions

-1
推荐指数
1
解决办法
81
查看次数

根据价值锁定/解锁?

我有一个方法,通过3个并发线程在对象实例上调用.我感兴趣的锁是基于价值而不是对象.例如,如果两个线程(T1,T2)正在处理RecordID = 123并且T3正在处理RecordID = 456.该方法应仅锁定T2,T3应继续执行.

目前,我正在使用Lock,但如果T1被锁定,它将锁定T2和T3.

public void doSomething(String id){
      try {
       lock.lock();
       MyRecord r = find(id);
       ...
       ....
       } finally{
         lock.unlock();
       }
}
Run Code Online (Sandbox Code Playgroud)

java multithreading synchronization locking thread-safety

-1
推荐指数
1
解决办法
1113
查看次数

如何编写线程安全的getInstance方法?

我的getInstance库中有一个在多个线程中使用的方法,但我不确定它是否是线程安全的:

protected static DataClient instance;

protected DataClient() {
    // do stuff here
}

public static synchronized void initialize() {
    if (instance == null) {
        instance = new DataClient();
    }
}

public static DataClient getInstance() {
    if (instance == null) {
        initialize();
    }
    return instance;
}
Run Code Online (Sandbox Code Playgroud)

这就是我使用它的方式:

DataClient.getInstance();
Run Code Online (Sandbox Code Playgroud)

这个线程是否安全,如果不是,那么谁能解释为什么它不是线程安全的?

java multithreading locking thread-safety

-1
推荐指数
1
解决办法
1014
查看次数

mutex.Lock和deferred mutex.Unock命令

在golang中,sync.Mutex Lock和Unlock是usul操作,但是Lock和defer Unlock的正确顺序是什么?

mu.Lock()
defer mu.Unlock()
Run Code Online (Sandbox Code Playgroud)

要么

defer mu.Unlock()
mu.Lock()
Run Code Online (Sandbox Code Playgroud)

哪个最好?

locking go deferred

-1
推荐指数
1
解决办法
395
查看次数

如何在调用其他使用unique_lock的函数的类中使用unique_lock?

我有一个类,我需要使线程安全.我试图通过在类中的每个函数的顶部放置一个独特的锁来做到这一点.问题是,只要一个函数调用另一个函数(在此类中),互斥锁似乎相互锁定,尽管它们处于不同的函数中.我怎么能阻止这种情况发生?

一个例子是一个带有get()和set()函数的类,它们在每个函数的开头都使用unique_lock.但是在set()中你想在某个时候调用get(),但是没有set()的互斥锁定get()的互斥锁.但是,如果直接调用,get()中的互斥锁仍然可以工作.

c++ mutex locking c++11

-1
推荐指数
1
解决办法
554
查看次数

无缓冲通道是否等待数据?

我有这个程序:

package main

import (
    "fmt"
    "time"
)

var ch1 = make(chan int)
var ch2 = make(chan int)

func f1() {
    select {
    case <-ch1:
        fmt.Println("ch1")
    }
}
func f2() {
    select {
    case <-ch2:
        fmt.Println("ch2")
    }
}
func main() {
    go f1()
    go f2()
    time.Sleep(2 * time.Second)
    fmt.Println("no buffered channel will wait?")
    ch1 <- 1
    ch2 <- 2
    fmt.Println("main exits")
}
Run Code Online (Sandbox Code Playgroud)

我想到的是,只要F1和F2不显示任何信息,这意味着CH1和CH2具有里面什么都没有,所以ch1<-1ch2<-2应该阻止?

但是当运行时,它会打印:

no buffered channel will wait?
main exits
Run Code Online (Sandbox Code Playgroud)

为什么那些无缓冲通道ch1,并ch2没有阻止内主? …

buffer locking channel go

-1
推荐指数
1
解决办法
85
查看次数

无法在锁中等待,如何确保不会从多个线程访问异步变量和方法?

我有以下代码:

public const int ThreadLimitMax = 128;
private static object setThreadLimitLock = new object();
private static SemaphoreSlim totalThreadLimiter = new SemaphoreSlim(ThreadLimit, ThreadLimitMax);
        
public static int ThreadLimit { get; private set; } = 128;

public static async Task SetThreadLimit(int max)
{
    if (max > ThreadLimitMax)
        throw new ArgumentOutOfRangeException(nameof(max), $"Cannot have more than {ThreadLimitMax} threads.");
    if (max < 1)
        throw new ArgumentOutOfRangeException(nameof(max), $"Cannot have less than 1 threads.");

    lock (setThreadLimitLock)
    {
        int difference = Math.Abs(ThreadLimit - max);
        if (max < ThreadLimit)
        { …
Run Code Online (Sandbox Code Playgroud)

c# multithreading semaphore locking thread-safety

-1
推荐指数
1
解决办法
46
查看次数

在那些简单的情况下使用 C# 锁有用吗?

在多线程环境中,锁定对线程敏感的资源很重要。我经常假设集合等是线程不安全的,具体取决于 MS 文档,但简单类型是否也是线程敏感的?

让我们举个例子。锁定 int 属性访问是否有用,例如

public int SomeProperty
{
    get
    {
        lock (_lock)
        {
             return _value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者是一个足够普通的吸气剂,即

public int SomeProperty => _value;
Run Code Online (Sandbox Code Playgroud)

据我了解,一个简单的字段读取是线程安全的,但我仍然在网上和一些代码库中看到第一个例子。

第二个问题,单行指令中的值是顺序读取还是同时读取?换句话说,我这样做时是否需要锁定

public TimeSpan GetSomeExampleValue()
{
    lock (_lock)
    {
        return _dateTime1 - _dateTime2;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者我可以简单地做

public TimeSpan GetSomeExampleValue()
{
    return _dateTime1 - _dateTime2;
}
Run Code Online (Sandbox Code Playgroud)

c# multithreading locking thread-safety thread-synchronization

-2
推荐指数
1
解决办法
62
查看次数