GVKun编程网logo

Scheduler&Task&Worker&Thread&Request&Session&Connection OF MSSQL

1

最近很多小伙伴都在问Scheduler&Task&Worker&Thread&Request&Session&ConnectionOFMSSQL这两个问题,那么本篇文章就来给大家详细解答一下,同时本文

最近很多小伙伴都在问Scheduler&Task&Worker&Thread&Request&Session&Connection OF MSSQL这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展android – Request.executeMeRequestAsync(session,Request.GraphUserCallback())函数的问题、Async / Await, Task.Run(async() => await), await Task.Run(()=>), await Task.Run(async() => await) 区别、avro-rpc 中协议定义的 request 的模式与 GenericRequest.request (String messageName, Object request) 中的 request 是一致对应的关系么、bitcoin task scheduler 使用等相关知识,下面开始了哦!

本文目录一览:

Scheduler&Task&Worker&Thread&Request&Session&Connection OF MSSQL

Scheduler&Task&Worker&Thread&Request&Session&Connection OF MSSQL

MSsql一直以来被人们认为简单、好学,但等到大家掌握了入门操作,深入理解起来又觉得非常的“拧巴”,尤其是对用惯了Oracle的同学来说,究其根本原因,无非是MSsql引入和暴露了太多的概念、细节和理论层,而Oracle恰恰屏蔽了这些,比如下面讲到的这些概念,即使是使用很久MSsql的同学来说,也未必就真理解的正确,下面这段文字,很好的解释了MSsql中的几个基本概念:

Scheduler (SOS Scheduler)– the object that manages thread scheduling in sql Server and allows threads to be exposed to the cpu (described in sys.dm_os_schedulers). This is the all-powerful but benign and graceful master whom everyone abides.  He does not control things but lets the workers work with each other and relies on their cooperation (co-operative scheduling mode). Each scheduler /master (one per logical cpu) accepts new tasks and hands them off to workers. SOS Scheduler allows one worker at a time to be exposed to the cpu.


Task –a task represents the work that needs to be performed (sys.dm_os_tasks). A task contains one of the following requests: query request (RPC event or Language event), a prelogin request (prelogin event),  a login request (connect event), a logout request (disconnect event), a query cancellation request (an Attention event), a bulk load request (bulk load event), a distributed transaction request (transaction manager event). A task is what the Master is about – it is what defines its existence. Note these are tracked at the SOS scheduler layer (thus dm_OS_tasks)


Worker (worker thread) – This is the logical sql Server representation of a thread (think of it as a wrapper on top of the OS thread). It is a structure within the Scheduler which maintains sql Server-specific information about what a worker thread does. sys.dm_os_workers. Workers are the humble servants who carry out the task assigned to them by the Master (scheduler).


Thread – this is the OS thread sys.dm_os_threads that is created via calls like CreateThread()/_beginthreadex(). A Worker is mapped 1-to-1 to a Thread.


Request is the logical representation of a query request made from the client application to sql Server (sys.dm_exec_requests). This query request has been assigned to a task that the scheduler hands off to a worker to process. This represents query requests as well as system thread operations (like checkpoint, log writer, etc); you will not find login, logouts, attentions and the like here. Also, note that this is a representation at the sql execution engine level (thus dm_EXEC_requests) not at the SOS Scheduler layer.


Sessions – when the client application connects to sql Server the two sides establish a "session" on which to exchange information. Strictly speaking a session is not the same as the underlying physical connection, it is a sql Server logical representation of a connection. But for practical purposes, you can think of this as being a connection (session =~ connection). See sys.dm_exec_sessions. This is the old SPID that existed in sql Server 2000 and earlier. You may sometimes notice a single session repeating multiple times in a DMV output. This happens because of parallel queries. A parallel query uses the same session to communicate with the client, but on the sql Server side multiple worker (threads) are assigned to service this request. So if you see multiple rows with the same session ID, kNow that the query request is being serviced by multiple threads.


Connections – this is the actual physical connection established at the lower protocol level with all of its characteristics sys.dm_exec_connections . There is a 1:1 mapping between a Session and a Connection.tr

android – Request.executeMeRequestAsync(session,Request.GraphUserCallback())函数的问题

android – Request.executeMeRequestAsync(session,Request.GraphUserCallback())函数的问题

我正在使用Facebook关注 Android应用程序登录教程.

我对哈希键和所有内容都有很多问题,我认为我已经解决了所有这些问题,因为我的会话已经处于OPENED状态.

我现在遇到的问题是,在我登录facebook后,当会话已经打开时,代码执行Request.executeMeRquestAsync()并且它永远不会进入onComplete()部分……任何想法?

这是代码……

package com.example.firstandroidapp;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;


import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;

public class MainActivity extends Activity {
@Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // start Facebook Login
    Session.openActiveSession(this,true,new Session.StatusCallback() {

      // callback when session changes state
      @Override
      public void call(Session session,SessionState state,Exception exception) {
          try {
                PackageInfo info = getPackageManager().getPackageInfo("com.example.firstandroidapp",PackageManager.GET_SIGNATURES);
                for (Signature signature : info.signatures) {
                    MessageDigest md = MessageDigest.getInstance("SHA");
                    md.update(signature.toByteArray());
                    Log.i("Digest: ",Base64.encodetoString(md.digest(),0));
                }
            } catch (NameNotFoundException e) {
                Log.e("Test",e.getMessage());
            } catch (NoSuchAlgorithmException e) {
                Log.e("Test",e.getMessage());
            }

          if (session.isOpened()) {

          // make request to the /me API
          Request.executeMeRequestAsync(session,new Request.GraphUserCallback() {

            // callback after Graph API response with user object
            @Override
            public void onCompleted(GraphUser user,Response response) {
              // it never gets here...
                  if (user != null) {
                TextView welcome = (TextView) findViewById(R.id.welcome);
                welcome.setText("Hello " + user.getName() + "!");
              }
            }
          });
        }
      }
    });
  }

  @Override
  public void onActivityResult(int requestCode,int resultCode,Intent data) {
      super.onActivityResult(requestCode,resultCode,data);
      Session.getActiveSession().onActivityResult(this,requestCode,data);
  }

}

Thanx非常提前.
大卫.

解决方法

我有同样的问题.

该教程告诉我们修改AndroidManifest.xml.在修改中,我将下面的标记放在错误的位置(我没有使用Eclipse来修改清单文件),这阻止了回调.

<manifest ...>
  ...
  <application ...>
    ...
    <activity android:name="com.facebook.LoginActivity"/>
    ...
    <Meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/>
    ...
  </application>
  ...
  <uses-permission android:name="android.permission.INTERNET"/>
  ...
</manifest>

尝试仔细检查您的AndroidManifest.xml. The official document会有所帮助.

Async / Await, Task.Run(async() => await), await Task.Run(()=>), await Task.Run(async() => await) 区别

Async / Await, Task.Run(async() => await), await Task.Run(()=>), await Task.Run(async() => await) 区别

如何解决Async / Await, Task.Run(async() => await), await Task.Run(()=>), await Task.Run(async() => await) 区别

嗨,我是 Xamarin 开发人员

我有一些关于使用异步编程的问题

当我调用 Webservice 时,我通常使用 async/await。

但是,如果它只使用一个线程(UI),那么在 UI 更改时会导致一些问题。

例如,在获取价值之前先处理代码,有时会挂起UI

我阅读了一些关于异步编程的文档或博客。这表明您可以解决使用 Task.RUN 时的问题

但是很难知道我的编程水平.....

这是一些例子,你能解释一下有什么不同吗?

notificationVos = await Task.Run(() => wSSmartConsoleCommon.getScmessage<NotificationVo>());

notificationVos = Task.Run(() => wSSmartConsoleCommon.getScmessage<NotificationVo>());

notificationVos = await wSSmartConsoleCommon.getScmessage<NotificationVo>());

notificationVos = await Task.Run(async() => await wSSmartConsoleCommon.getScmessage<NotificationVo>());

avro-rpc 中协议定义的 request 的模式与 GenericRequest.request (String messageName, Object request) 中的 request 是一致对应的关系么

avro-rpc 中协议定义的 request 的模式与 GenericRequest.request (String messageName, Object request) 中的 request 是一致对应的关系么

@蝙蝠 你好,想请教个问题:在 avro-rpc 中,如果协议是下面这样子:


{
  "namespace": "com.acme",
  "protocol": "HelloWorld",
  "doc": "Protocol Greetings",

  "types": [
    {"name": "Greeting", "type": "record", "fields": [
      {"name": "message", "type": "string"}]},
    {"name": "Curse", "type": "error", "fields": [
      {"name": "message", "type": "string"}]}
  ],

  "messages": {
    "hello": {
      "doc": "Say hello.",
      "request": [{"name": "greeting", "type": "Greeting" }],
      "response": "Greeting",
      "errors": ["Curse"]
    }
  }
}
那么在
public Object GenericRequest.request(String messageName, Object request)
               throws IOException
中间 request 应该传什么样的值呢,是 GenericRecord 类型的还是怎样?本质上想问的是,这里的 request 和协议中定义的 "request" 的 schema 之间的关系是怎么样的?


bitcoin task scheduler 使用

bitcoin task scheduler 使用

bitcoin 进程启动后,有一个专门的线程做任务调度, 这些任务根据指定的时刻,执行对应的函数:

bool AppInitMain()
{
   .......
   // Start the lightweight task scheduler thread
    CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
    threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
   .......
}

调度器类主要是实现了一个生产者消费者的任务队列, 只是这个任务队列是用 std::multimap 实现的,map 的 key 表达某一时刻, map 的值表达, 那一时刻要执行的函数, 内部使用条件变量和锁来保护 multimap,和几个 bool 条件:

class CScheduler
{
public:
    CScheduler();
    ~CScheduler();
    
    typedef std::function<void(void)> Function;
    
    void schedule(Function f, boost::chrono::system_clock::time_point t=boost::chrono::system_clock::now());
    void scheduleFromNow(Function f, int64_t deltaMilliSeconds);
    void scheduleEvery(Function f, int64_t deltaMilliSeconds);
    void serviceQueue();
    void stop(bool drain=false);
    size_t getQueueInfo(boost::chrono::system_clock::time_point &first,
                        boost::chrono::system_clock::time_point &last) const;
    bool AreThreadsServicingQueue() const;

private:
    std::multimap<boost::chrono::system_clock::time_point, Function> taskQueue;
    boost::condition_variable newTaskScheduled;
    mutable boost::mutex newTaskMutex;
    int nThreadsServicingQueue;
    bool stopRequested;
    bool stopWhenEmpty;
    bool shouldStop() const { return stopRequested || (stopWhenEmpty && taskQueue.empty()); }
};

CScheduler 的 client 通过调用 schedule 往内部 multimap 添加一个条目;scheduleFromNow 和 scheduleEvery 内部都是调用 schedule 方法实现;这三个方法属于生产者要生产任务的方法, 任务的消费者调用 serviceQueue 等待取走任务, 然后执行。 目前整个程序有一个全局的 CScheduler 实例:

  static CScheduler scheduler;

这个实例对应只有一个消费者线程, 即唯一的后台调度器线程。 class SingleThreadedSchedulerClient 主要用途是,借助 CScheduler 类型,保障被添加到内部链表的任务, 被串行执行:

class SingleThreadedSchedulerClient {
private:
    CScheduler *m_pscheduler;

    CCriticalSection m_cs_callbacks_pending;
    std::list<std::function<void (void)>> m_callbacks_pending;
    bool m_are_callbacks_running = false;
    void MaybeScheduleProcessQueue();
    void ProcessQueue();
    
public:
    explicit SingleThreadedSchedulerClient(CScheduler *pschedulerIn) : m_pscheduler(pschedulerIn) {}
    void AddToProcessQueue(std::function<void (void)> func);
    void EmptyQueue();
    size_t CallbacksPending();
};

基本的使用例子:

#include <scheduler.h>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/test/unit_test.hpp>
#include <iostream>

static void doN(){
	std::cout << "output now\n";
}
static void doE(){
	for(int i = 0; i < 10; i++){
		std::cout << "i = " << i << ''\n'';
	}
	std::cout << ''\n'';
}

BOOST_AUTO_TEST_SUITE(sche_tests)
BOOST_AUTO_TEST_CASE(sche)
{
    CScheduler s;
    s.scheduleFromNow(doN, 1000); 
    s.scheduleEvery(doE, 1000); 
    boost::thread t(boost::bind(&CScheduler::serviceQueue, &s));
    boost::this_thread::sleep_for(boost::chrono::seconds{5});
    t.interrupt();
    t.join();
}

BOOST_AUTO_TEST_CASE(singlethread)
{
    CScheduler s;
    SingleThreadedSchedulerClient  sc (&s);
    for(int i = 1; i <11; i++){
	    auto  f = [=]{
		    std::cout << "thread " << boost::this_thread::get_id() << " print arg: " << i << ''\n'';
	    };
            sc.AddToProcessQueue(f);
    }
    boost::thread t(boost::bind(&CScheduler::serviceQueue, &s));
    boost::this_thread::sleep_for(boost::chrono::seconds{1});
    t.interrupt();
    t.join();
}
BOOST_AUTO_TEST_SUITE_END()

进程启动后, 全局对象连接管理器 connman 初始化后, connman 的 Start 方法最后,通过 scheduler 线程安排了一个定时任务:每隔 15 分钟, 把 connman 对象内部成员,banmap_t 类型的 setBanned, CAddrMan 类型的 addrman 序列化到本地文件 banlist.dat 和 peers.dat。

//init.cpp
if (!connman.Start(scheduler, connOptions)) {
        return false;
}
//net.cpp
bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
{
    ...............
    scheduler.scheduleEvery(std::bind(&CConnman::DumpData, this), DUMP_ADDRESSES_INTERVAL * 1000);
}

如果钱包功能编译使能,让 scheduler 线程安排,每隔 500 毫秒刷新钱包状态。

//init.cpp 
#ifdef ENABLE_WALLET
    StartWallets(scheduler);
#endif

//wallet/init.cpp 
void StartWallets(CScheduler& scheduler) {
    for (CWalletRef pwallet : vpwallets) {
        pwallet->postInitProcess(scheduler);
    }
}

//wallet/wallet.cpp 
void CWallet::postInitProcess(CScheduler& scheduler)
{
    ReacceptWalletTransactions();
    if (!CWallet::fFlushScheduled.exchange(true)) {
        scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
    }
}

PeerLogicValidation 对象的构造函数内部,scheduler 线程安排每 45 秒执行 CheckForStaleTipAndEvictPeers, CheckForStaleTipAndEvictPeer 函数主要做两件事: 1. 关掉多余的外出 tcp 连接, 2. 根据当前时间,检查当前节点的 blockchain 的 tip 是否有可能过时了,建立额外的连接同步跟上。

PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn, CScheduler &scheduler) : connman(connmanIn), m_stale_tip_check_time(0) {
    // Initialize global variables that cannot be constructed at startup.
    recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));

    const Consensus::Params& consensusParams = Params().GetConsensus();
    // Stale tip checking and peer eviction are on two different timers, but we
    // don''t want them to get out of sync due to drift in the scheduler, so we
    // combine them in one function and schedule at the quicker (peer-eviction)
    // timer.
    static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
    scheduler.scheduleEvery(std::bind(&PeerLogicValidation::CheckForStaleTipAndEvictPeers, this, consensusParams), EXTRA_PEER_CHECK_INTERVAL * 1000);
}

void PeerLogicValidation::CheckForStaleTipAndEvictPeers(const Consensus::Params &consensusParams)
{
    if (connman == nullptr) return;

    int64_t time_in_seconds = GetTime();

    EvictExtraOutboundPeers(time_in_seconds);

    if (time_in_seconds > m_stale_tip_check_time) {
        LOCK(cs_main);
        // Check whether our tip is stale, and if so, allow using an extra
        // outbound peer
        if (TipMayBeStale(consensusParams)) {
            LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", time_in_seconds - g_last_tip_update);
            connman->SetTryNewOutboundPeer(true);
        } else if (connman->GetTryNewOutboundPeer()) {
            connman->SetTryNewOutboundPeer(false);
        }
        m_stale_tip_check_time = time_in_seconds + STALE_CHECK_INTERVAL;
    }
}

关于Scheduler&Task&Worker&Thread&Request&Session&Connection OF MSSQL的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于android – Request.executeMeRequestAsync(session,Request.GraphUserCallback())函数的问题、Async / Await, Task.Run(async() => await), await Task.Run(()=>), await Task.Run(async() => await) 区别、avro-rpc 中协议定义的 request 的模式与 GenericRequest.request (String messageName, Object request) 中的 request 是一致对应的关系么、bitcoin task scheduler 使用等相关知识的信息别忘了在本站进行查找喔。

本文标签: